<repo_name>zccmark/pcart<file_sep>/application/models/Staff_model.php
<?php

class Staff_model extends MY_Model
{
    public $table = 'staff';
    public $primary_key = 'stId';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->return_as = 'array';

        $this->has_one['retail'] = array('foreign_model' => 'Retail_model', 'foreign_table' => 'retail', 'foreign_key' => 'rId', 'local_key' => 'rId_link');
        $this->has_one['country'] = array('foreign_model' => 'Country_model', 'foreign_table' => 'country', 'foreign_key' => 'cyId', 'local_key' => 'cyId_link');
        $this->has_one['area'] = array('foreign_model' => 'Area_model', 'foreign_table' => 'area', 'foreign_key' => 'aaId', 'local_key' => 'aaId_link');
    }
}

?>
<file_sep>/application/views/coupon/edit.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">貴賓優惠券序號登錄</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>優惠券張數</label>
                    <input type="number" name="qty" class="form-control text-right" required />
                </div>

                <div class="form-group">
                    <label>首張優惠券序號</label>
                    <input name="first_couponNum" class="form-control" value="" />
                </div>

                <div class="form-group">
                    <label>末張優惠券序號</label>
                    <input name="last_couponNum" class="form-control" value="" />
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/coupon/overview')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="更新"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/stock_counting/edit.php
<div class="container">
    <h1 class="mb-4 text-center">盤盈虧報表編輯</h1>

    <div class="form-group row">
        <label class="col-sm-2 col-form-label font-weight-bold">盤點事由</label>
        <div class="col-sm-10">
            <?= $counting_reason ?>
        </div>
    </div>

    <div class="form-group row">
        <label class="col-sm-2 col-form-label font-weight-bold">承辦人</label>
        <div class="col-sm-10">
            <?= $dealer['name'] ?>
        </div>
    </div>

    <form method="post" id="countingForm" enctype="multipart/form-data">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>


        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th>項次</th>
                <th>貨品編號<br />貨品名稱</th>
                <th>盤點內容</th>
            </tr>
            <?php if ($products) {
                $i = 1;
                foreach ($products as $product_id => $product) {
                    ?>
                    <tr class="<?= ($product['pKind'] == '3') ? ' olive_bg' : '' ?>">
                        <td class="text-center"><?= $i ?></td>
                        <td>
                            <?= $product['p_num'] ?><br />
                            <?= $product['pdName'] ?> <?= $product['intro2'] ?>
                        </td>
                        <td>
                            <table class="table table-hover table-bordered">
                                <tr>
                                    <th class="text-right">原數量</th>
                                    <th>到期日</th>
                                    <th class="text-right">數量</th>
                                    <th>盤點盈虧</th>
                                    <th style="width: 300px;">盤差說明</th>
                                    <th>附件</th>
                                </tr>
                                <?php
                                if ($product['stocks']){
                                    foreach ($product['stocks'] as $k => $s) {
                                        ?>
                                        <tr class="product_stock">
                                            <td class="text-right product_stock_original"><?= $s['stock'] ?></td>
                                            <td>
                                                <input type="date" name="items[<?= $product_id ?>][<?= $k ?>][date]"
                                                       class="item_date form-control"
                                                       value="<?= set_value('items[' . $product_id . '][' . $k . '][date]', $s['expired_at']) ?>"
                                                       style="width: 200px;"
                                                />
                                            </td>
                                            <td>
                                                <input type="number" name="items[<?= $product_id ?>][<?= $k ?>][qty]"
                                                       min="0" class="item_qty form-control text-right"
                                                       data-stock="<?= $s['stock'] ?>"
                                                       value="<?= set_value('items[' . $product_id . '][' . $k . '][qty]', $s['stock']) ?>"
                                                       style="width: 120px;"
                                                />
                                            </td>
                                            <td class="item_diff text-right"></td>
                                            <td>
                                                <div class="input-group">
                                                    <?php
                                                    echo form_dropdown('items[' . $product_id . '][' . $k . '][diff_reason]', $diff_reason, '', 'class="item_diff_reason form-control" disabled');
                                                    ?>
                                                    <input name="items[<?= $product_id ?>][<?= $k ?>][diff_reason_text]"
                                                           maxlength="200"
                                                           class="item_diff_reason_text form-control d-none" disabled
                                                           required value="" placeholder="盤差說明"/>
                                                </div>
                                            </td>
                                            <td>
                                                <input type="file" class="input_diff_files form-control-file" disabled
                                                       name="diff_files[<?= $product_id ?>][<?= $k ?>]"
                                                       style="min-width: 120px;"/>
                                            </td>
                                        </tr>
                                        <?php
                                    }
                                } else {
                                    $k = 0;
                                ?>
                                    <tr class="product_stock">
                                        <td class="text-right product_stock_original">0</td>
                                        <td>
                                            <input type="date" name="items[<?= $product_id ?>][<?= $k ?>][date]"
                                                   class="item_date form-control"
                                                   value="<?= set_value('items[' . $product_id . '][' . $k . '][date]') ?>"
                                                   style="width: 200px;"
                                            />
                                        </td>
                                        <td>
                                            <input type="number" name="items[<?= $product_id ?>][<?= $k ?>][qty]"
                                                   min="0" class="item_qty form-control text-right"
                                                   data-stock="0"
                                                   value="<?= set_value('items[' . $product_id . '][' . $k . '][qty]') ?>"
                                                   style="width: 120px;"
                                            />
                                        </td>
                                        <td class="item_diff text-right"></td>
                                        <td>
                                            <div class="input-group">
                                                <?php
                                                echo form_dropdown('items[' . $product_id . '][' . $k . '][diff_reason]', $diff_reason, '', 'class="item_diff_reason form-control" disabled');
                                                ?>
                                                <input name="items[<?= $product_id ?>][<?= $k ?>][diff_reason_text]"
                                                       maxlength="200"
                                                       class="item_diff_reason_text form-control d-none" disabled
                                                       required value="" placeholder="盤差說明"/>
                                            </div>
                                        </td>
                                        <td>
                                            <input type="file" class="input_diff_files form-control-file" disabled
                                                   name="diff_files[<?= $product_id ?>][<?= $k ?>]"
                                                   style="min-width: 120px;"/>
                                        </td>
                                    </tr>
                                <?php
                                }
                                ?>
                                <tr class="product_stock_add">
                                    <td colspan="6">
                                        <input type="button" class="btn btn-warning btn-add-expired"
                                               data-product="<?= $product_id ?>" data-index="<?= $k ?>"
                                               value="新增到期日"/>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <?php
                    $i++;
                }
            }
            ?>
        </table>
        <div class="form-group text-center">
            <input type="submit" name="submit_cancel" class="btn btn-warning mr-2" value="取消│不儲存"/>
            <input type="submit" name="submit_save" class="btn btn-success" value="新增完成│儲存送出"/>
        </div>
    </form>
</div>

<script>
    $().ready(function () {
        $('.btn-add-expired').on('click', function(){
            var index = $(this).data('index') + 1;
            var product_id = $(this).data('product');
            $(this).data('index', index);
            var html = $(this).parents('tr.product_stock_add').prev().clone();
            html.find('td.product_stock_original').text('');
            html.find('input.item_date').prop('name', 'items[' + product_id + '][' + index + '][date]').val('');
            html.find('input.item_qty').prop('name', 'items[' + product_id + '][' + index + '][qty]').val('').data('stock', 0);
            html.find('select.item_diff_reason').prop('name', 'items[' + product_id + '][' + index + '][diff_reason]').prop('selected', false);
            html.find('input.input_diff_files').prop('name', 'diff_files[' + product_id + '][' + index + ']').val('');
            $(this).parents('tr.product_stock_add').before(html);
            $(this).parents('tr.product_stock_add').prev().find('input.item_qty').trigger('change');
        });

        $(document).on('change',"input.item_qty",function () {
            var qty = parseInt($(this).val()) || 0;
            var stock = parseInt($(this).data('stock')) || 0;
            $(this).parents('tr.product_stock').find('.item_diff').text((qty - stock));
            if (qty == stock){
                $(this).parents('tr.product_stock').find('.item_diff_reason').val('').prop('disabled', true);
                $(this).parents('tr.product_stock').find('.item_diff_reason_text').addClass('d-none').val('').prop('disabled', true);
                $(this).parents('tr.product_stock').find('.input_diff_files').val('').prop('disabled', true);
            } else {
                $(this).parents('tr.product_stock').find('.item_diff_reason').prop('disabled', false);
                $(this).parents('tr.product_stock').find('.item_diff_reason_text').prop('disabled', false);
                $(this).parents('tr.product_stock').find('.input_diff_files').prop('disabled', false);
            }
        });

        $('.item_diff_reason').change(function () {
            var item_diff_reason = parseInt($(this).val());
            if (item_diff_reason == 2) {
                $(this).next().val('').prop('disabled', false).removeClass('d-none');
            } else {
                $(this).next().val('').prop('disabled', true).addClass('d-none');
            }
        });

        $("#countingForm").find('input[type="submit"]').click(function (e) {
            $.each($('.item_date'), function(){
                if ($(this).val() == ''){
                    $(this).prop('disabled', true);
                }
            });

            $.each($('.item_qty'), function(){
                if ($(this).val() == ''){
                    $(this).prop('disabled', true);
                }
            });

            $.each($('.item_diff_reason'), function(){
                if ($(this).val() == ''){
                    $(this).prop('disabled', true);
                }
            });

            $.each($('.item_diff_reason_text'), function(){
                if ($(this).val() == ''){
                    $(this).prop('disabled', true);
                }
            });

            $.each($('.input_diff_files'), function(){
                if ($(this).val() == ''){
                    $(this).prop('disabled', true);
                }
            });
        });
    });
</script><file_sep>/application/views/commission/dealers.php
<div class="container">
        <button type="button" class="btn btn-success float-right" data-toggle="modal" data-target="#salesModal">
            輔銷人定義
        </button>

    <h1 class="mb-4">輔銷人名單</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">經銷單位</th>
            <th class="text-center">輔銷單位</th>
            <th class="text-center">輔銷人</th>
            <th class="text-center">輔銷人獎金</th>
        </tr>
        <?php
        if ($retailers) {
            foreach ($retailers as $retailer) {
                ?>
                <tr>
                    <td class="text-center"><?= $retailer['company'] ?></td>
                    <td class="text-center"><?= empty($retailer['sales_retailer']) ? '' : $retailer['sales_retailer']['company'] ?></td>
                    <td class="text-center"><?= empty($retailer['sales_dealer']) ? '' : $retailer['sales_dealer']['name'] ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php if ($retailer['sales_dealer_id'] && !empty($authority['dealer'])){ ?>
                            <a class="btn btn-info btn-sm"
                               href="<?= base_url('/commission/dealer/' . $retailer['sales_dealer_id']) ?>">明細</a>
                            <?php } ?>
                        </div>

                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="4" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>
</div>


<div class="modal fade" id="salesModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">輔銷人定義</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>輔銷人：開發引介經銷商之輔銷單位人員(即員工或股東)或經銷商；即經銷商首次登錄時所用帳密的所有人。”</p>
                <p>輔銷人為經銷商時，「輔銷單位」為「總經銷」；輔銷人非經銷商、即為「皮瑪斯門市(或總經銷) 」之「人員或股東」時，輔銷單位為「皮瑪斯門市」或「總經銷」。但經銷櫃位Ｂ、及全部之經銷店面之「輔銷單位」為「總經銷」。</p>
                <p>輔銷人之輔導金，由輔銷單位發放。</p>
            </div>
        </div>
    </div>
</div><file_sep>/application/views/payment/add.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">新增付款紀錄</h1>

            <form method="post" enctype="multipart/form-data">
                <?php if ($error) { ?>
                    <div class="alert alert-danger">
                        <?= implode('<br>', $error) ?>
                    </div>
                <?php } ?>
                
                <div class="form-group">
                    <label class="font-weight-bold">付款金額</label>
                    <div>
                    $<?=number_format($payment['price'])?>
                    </div>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">付款單位</label>
                    <div><?=$payment['paid_retailer']['company']?></div>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">收款單位</label>
                    <div><?=$payment['received_retailer']['company']?></div>
                </div>

                <div id="bank_info" class="d-none">
                    <div class="form-group">
                        <label class="font-weight-bold">收款銀行</label>
                        <div><?=$payment['received_retailer']['bank']?></div>
                    </div>

                    <div class="form-group">
                        <label class="font-weight-bold">分行名</label>
                        <div><?=$payment['received_retailer']['bank_branch']?></div>
                    </div>

                    <div class="form-group">
                        <label class="font-weight-bold">收款戶名</label>
                        <div><?=$payment['received_retailer']['bank_account_title']?></div>
                    </div>

                    <div class="form-group">
                        <label class="font-weight-bold">收款帳戶</label>
                        <div><?=$payment['received_retailer']['bank_account']?></div>
                    </div>
                </div>

                <div class="form-group">
                    <label>付款方式</label>
                    <?php
                    echo form_dropdown('type_id', paymentType(), set_value('type_id'), 'id="payment_type" class="form-control"');
                    ?>
                </div>

                <div class="form-group" id="receipt_wrap">
                    <label class="font-weight-bold">上傳付款憑證</label>
                    <input type="file" class="form-control-file" name="receipt" required />
                </div>
                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/payment/overview')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="送出已付款訊息"/>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    $().ready(function () {
        $('#payment_type').change(function(){
            if ($(this).val() == '2'){ //匯款
                $('#receipt_wrap').removeClass('d-none').find('input[name="receipt"]').prop('required', true);
                $('#bank_info').removeClass('d-none');
            } else {
                $('#receipt_wrap').addClass('d-none').find('input[name="receipt"]').prop('required', false);
                $('#bank_info').addClass('d-none');
            }
        });

        $('#payment_type').trigger('change');
    });
</script><file_sep>/application/controllers/Supervisor.php
<?php

class Supervisor extends MY_Controller
{
    protected $dealer;

    public $threshold_categories;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged())) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_model');
        $this->load->model('retailer_relationship_model');
        $this->load->model('retailer_level_model');
        $this->load->model('purchase_model');
        $this->load->model('shipment_model');
        $this->load->library('purchase_lib');

        $this->threshold_categories = [
            1 => '未達門檻之經銷商',
            2 => '已達門檻之經銷商',
            3 => '超過門檻之經銷商',
        ];

        $this->session->set_userdata('return_page', base_url('/supervisor/overview'));
    }

    public function overview()
    {
        $sales_retailer_select = [];
        $sales_dealer_select = [];
        if ($this->dealer['retailer_role_id'] == 2){
            $_retailers = $this->retailer_model
                ->with_sales_retailer()
                ->with_sales_dealer(['with' => ['relation' => 'retailer', 'fields' => 'company']])
                ->where('sales_retailer_id IS NOT NULL', null, null, false, false, true)
                ->where('sales_dealer_id IS NOT NULL', null, null, false, false, true)
                ->get_all();
            if ($_retailers){
                foreach ($_retailers as $r){
                    $sales_retailer_select[$r['sales_retailer_id']] = $r['sales_retailer']['company'];
                    $sales_dealer_select[$r['sales_dealer_id']] = '(' . $r['sales_dealer']['retailer']['company'] . ')' . $r['sales_dealer']['name'];
                }
            }
        }

        $sales_retailer_id = (int)$this->input->get('sales_retailer_id');
        if (!$sales_retailer_id || empty($sales_retailer_select[$sales_retailer_id])){
            $sales_retailer_id = null;
        }

        $sales_dealer_id = (int)$this->input->get('sales_dealer_id');
        if (!$sales_dealer_id || empty($sales_dealer_select[$sales_dealer_id])){
            $sales_dealer_id = null;
        }

        $year = (int)$this->input->get('year');
        $month = (int)$this->input->get('month');

        $year = $year ? $year : date('Y');
        $month = $month ? $month : date('m');

        $retailer_level_selects = $this->retailer_level_model->getLevelSelect();
        $retailer_level_id = (int)$this->input->get('retailer_level_id');
        if (!$retailer_level_id || empty($retailer_level_selects[$retailer_level_id])){
            $retailer_level_id = null;
        }

        $threshold_category = (int)$this->input->get('threshold_category');
        if (!$threshold_category || empty($this->threshold_categories[$threshold_category])){
            $threshold_category = null;
        }

        $disabled = 0;
        if (!empty($this->input->get('disabled'))){
            $disabled = 1;
        }

        $search = array(
            'year' => $year,
            'month' => $month,
            'retailer_level_id' => $retailer_level_id,
            'threshold_category' => $threshold_category,
            'sales_retailer_id' => $sales_retailer_id,
            'sales_dealer_id' => $sales_dealer_id,
            'disabled' => $disabled,
        );

        $retailers = [];
        $pagination = '';

        $_relationships = $this->retailer_relationship_model
            ->where('relation_type', 'supervisor')
            ->where('relation_retailer_id', $this->dealer['retailer_id'])
            ->get_all();
        if ($_relationships){
            $relationship_ids = [];
            foreach ($_relationships as $relationship){
                array_push($relationship_ids, $relationship['retailer_id']);
            }

            if ($relationship_ids){
                if ($search['retailer_level_id']){
                    $this->retailer_model->where('retailer_level_id', $search['retailer_level_id']);
                }

                $next_month_first_day = date('Y-m-d', strtotime('first day of next month ' . $search['year'] . '-' . $search['month'] . '-1'));

                $total_retailers_count = $this->retailer_model
                    ->where('id', $relationship_ids)
                    ->where('created_at', '<', $next_month_first_day)
                    ->count_rows();

                if ($search['retailer_level_id']){
                    $this->retailer_model->where('retailer_level_id', $search['retailer_level_id']);
                }

                if ($search['disabled']){
                    $this->retailer_model->where('disabled_at IS NOT NULL', null, null, false, false, true);
                } else {
                    $this->retailer_model->where('disabled_at IS NULL', null, null, false, false, true);
                }

                $_retailers = $this->retailer_model
                    ->with_sales_retailer()
                    ->with_sales_dealer()
                    ->with_role()
                    ->with_level(['with' => ['relation' => 'type']])
                    ->where('id', $relationship_ids)
                    ->where('created_at', '<', $next_month_first_day)
                    ->paginate(20, $total_retailers_count);

                if ($_retailers){
                    foreach ($_retailers as $retailer) {
                        if ($search['sales_retailer_id'] && $search['sales_retailer_id'] != $retailer['sales_retailer_id']){
                            continue;
                        }

                        if ($search['sales_dealer_id'] && $search['sales_dealer_id'] != $retailer['sales_dealer_id']){
                            continue;
                        }

                        $retailer_total_purchases = $this->purchase_lib->getRetailerTotalPurchases($retailer['id'], $next_month_first_day);
                        $first_total = $retailer_total_purchases['first_total'];
                        $first_at = $retailer_total_purchases['first_at'];
                        $total = $retailer_total_purchases['total'];
                        if (!$first_at){
                            continue;
                        }

                        if (empty($retailer['level'])) {
                            $retailer['level_title'] = $retailer['role']['title'];
                            $retailer['threshold'] = $retailer['purchaseThreshold'];
                        } else {
                            $retailer['level_title'] = $retailer['level']['type']['title'] . ' ' . $retailer['level']['code'];
                            $retailer['threshold'] = $retailer['purchaseThreshold'] ? $retailer['purchaseThreshold'] : $retailer['level']['monthThreshold'];
                        }
                        $first_month_diff = $this->purchase_lib->get_month_diff($first_at, $next_month_first_day);

                        $retailer['first'] = false;
                        $retailer['under'] = 0;
                        $retailer['over'] = 0;
                        $retailer['total'] = 0;

                        $table = $this->purchase_model->get_table_name();
                        $search_total_purchases = $this->purchase_model
                            ->fields('SUM(' . $table . '.subtotal) as total')
                            ->where('YEAR(created_at) = "' . $search['year'] . '"', null, null, false, false, true)
                            ->where('MONTH(created_at) = "' . $search['month'] . '"', null, null, false, false, true)
                            ->where('retailer_id', $retailer['id'])
                            ->where('isConfirmed', 1)
                            ->get();

                        if ($search_total_purchases) {
                            $retailer['total'] = $search_total_purchases['total'] ? $search_total_purchases['total'] : 0;
                        }

                        if ($first_month_diff == 1){
                            $retailer['first'] = true;
                            $retailer['under'] = 0;
                            $retailer['over'] = $retailer['total'] - $first_total - $retailer['threshold'];
                            if ($retailer['over'] < 0) {
                                $retailer['over'] = 0;
                            }
                        } else {
                            $search_diff = $total - $first_total - $retailer['threshold'] * $first_month_diff;
                            if ($search_diff < 0) {
                                $retailer['under'] = abs($search_diff);
                                if ($retailer['under'] > $retailer['threshold']){
                                    $retailer['under'] = $retailer['threshold'];
                                }
                                $retailer['over'] = 0;
                            } elseif ($search_diff > 0) {
                                $retailer['under'] = 0;
                                $retailer['over'] = $search_diff;
                            }
                        }

                        if (!$threshold_category || ($threshold_category == 1 && $retailer['under'] > 0) || ($threshold_category == 2 && $retailer['under'] == 0 && $retailer['over'] == 0) || ($threshold_category == 3 && $retailer['over'] > 0)){
                            $retailers[] = $retailer;
                        }
                    }

                    $pagination = $this->retailer_model->all_pages;
                }
            }
        }

        $this->load->helper('form');

        //權限設定
        $authority = array();
        if ($this->authentic->authority('supervisor', 'purchase')){
            $authority['purchase'] = true;
        }
        if ($this->authentic->authority('supervisor', 'info')){
            $authority['info'] = true;
        }

        $data = [
            'search' => $search,
            'sales_retailer_select' => $sales_retailer_select,
            'sales_dealer_select' => $sales_dealer_select,
            'retailer_level_selects' => $retailer_level_selects,
            'threshold_categories' => $this->threshold_categories,
            'retailers' => $retailers,
            'pagination' => $pagination,
            'authority' => $authority,
            'title' => '經銷商列表',
            'view' => 'supervisor/overview',
        ];

        $this->_preload($data);
    }

    public function info($retailer_id)
    {
        $retailer = $this->retailer_model
            ->with_sales_retailer()
            ->with_sales_dealer()
            ->with_role()
            ->with_contact_dealer()
            ->with_level(['with' => ['relation' => 'type']])
            ->get($retailer_id);

        if (!$retailer_id || !$retailer) {
            show_error('查無經銷單位資料');
        }

        if (empty($retailer['level'])) {
            $retailer['level_title'] = $retailer['role']['title'];
        } else {
            $retailer['level_title'] = $retailer['level']['type']['title'] . ' ' . $retailer['level']['code'];
        }

        $data = [
            'retailer' => $retailer,
            'title' => '經銷單位基本資料',
            'view' => 'supervisor/info',
        ];

        $this->_preload($data);
    }

    public function purchase($retailer_id, $year, $month)
    {
        $retailer = $this->retailer_model
            ->get($retailer_id);

        if (!$retailer_id || !$retailer) {
            show_error('查無經銷單位資料');
        }

        $year = (int)$year;
        $month = (int)$month;

        if (!$year || !$month || $month > 12){
            show_error('月份錯誤');
        }

        $purchases = $this->purchase_model
            ->with_retailer()
            ->with_shipout_retailer()
            ->where('YEAR(created_at) = "' . $year . '"', null, null, false, false, true)
            ->where('MONTH(created_at) = "' . $month . '"', null, null, false, false, true)
            ->where('retailer_id', $retailer_id)
            ->where('isConfirmed', 1)
            ->get_all();

        //權限設定
        $authority = array();
        if ($this->authentic->authority('supervisor', 'detail')){
            $authority['detail'] = true;
        }

        $data = [
            'retailer' => $retailer,
            'purchases' => $purchases,
            'authority' => $authority,
            'title' => '經銷商進貨明細',
            'view' => 'supervisor/purchase',
        ];

        $this->_preload($data);
    }

    public function detail($purchase_id)
    {
        $purchase = $this->purchase_model
            ->with_transfer_from()
            ->with_retailer('fields:company,invoice_title')
            ->with_shipin_retailer('fields:company,invoice_title')
            ->with_shipout_retailer('fields:company,invoice_title')
            ->with_order_transfer(['with' =>
                [
                    ['relation' => 'order', 'with' => ['contact']],
                    ['relation' => 'retailer'],
                    ['relation' => 'shipout_retailer'],
                ]
            ])
            ->with_items(['with' =>
                [
                    'relation' => 'product',
                    'with' => ['relation' => 'product_kind', 'fields' => 'ctName']
                ]
            ])
            ->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
            ->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
            ->get($purchase_id);

        if (!$purchase_id || !$purchase) {
            show_error('查無進貨單資料');
        }

        $purchase_lib = new purchase_lib($purchase);
        $purchase['paid_label'] = $purchase_lib->generatePaidLabel(true);
        $purchase['confirm_label'] = $purchase_lib->generateConfirmLabel(true);
        $purchase['shipped_label'] = $purchase_lib->generateShippedLabel();
        $shipments = [];
        $allowance_payments = [];
        $total_allowance_payment = 0;

        if ($purchase['isShipped']) {
            $real_shipin_retailer = $purchase['shipin_retailer'];
            $real_shipout_retailer = $purchase['shipout_retailer'];
            if (!is_null($purchase['transfer_id'])){
                $transfer_to_purchase = $this->purchase_model
                    ->with_shipin_retailer('fields:company,invoice_title')
                    ->with_shipout_retailer('fields:company,invoice_title')
                    ->get($purchase['transfer_id']);
                if ($transfer_to_purchase){
                    $real_shipout_retailer = $transfer_to_purchase['shipout_retailer'];
                }
            }

            $this->load->model('payment_model');
            //銷貨折讓
            $payments = $this->payment_model
                ->with_paid_retailer('fields:company,invoice_title')
                ->with_received_retailer('fields:company,invoice_title')
                ->with_confirm(['non_exclusive_where' => "confirm_type='payment'"])
                ->where('pay_type', 'shipment_allowance')
                ->where('pay_id', $purchase_id)
                ->get_all();
            if ($payments) {
                foreach ($payments as $payment){
                    $payment['payment_confirm_label'] = $this->payment_model->generatePaymentConfirmLabel($payment, true);
                    $allowance_payments[] = $payment;

                    if ($payment['active'] && $payment['isConfirmed']) {
                        $total_allowance_payment += $payment['price'];
                    }
                }
            }

            $_shipments = $this->shipment_model
                ->with_expirations(['with' => ['relation' => 'product']])
                ->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
                ->with_shipin_retailer('fields:company,invoice_title')
                ->with_shipout_retailer('fields:company,invoice_title')
                ->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
                ->where('ship_type', 'purchase')
                ->where('ship_id', $purchase_id)
                ->order_by('id', 'asc')
                ->get_all();

            if ($_shipments){
                foreach ($_shipments as $shipment){
                    if ($shipment['shipin_retailer_id'] != $purchase['retailer_id']){
                        $shipment['isReturn'] = true;
                        $shipment['shipout_retailer'] = $real_shipin_retailer;
                        $shipment['shipin_retailer'] = $real_shipout_retailer;
                    } else {
                        $shipment['shipout_retailer'] = $real_shipout_retailer;
                        $shipment['shipin_retailer'] = $real_shipin_retailer;
                    }
                    $shipments[] = $shipment;

                    if (is_null($shipment['shipment_id'])) {
                        $revised = $this->shipment_model
                            ->with_expirations(['with' => ['relation' => 'product']])
                            ->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
                            ->with_shipin_retailer('fields:company,invoice_title')
                            ->with_shipout_retailer('fields:company,invoice_title')
                            ->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
                            ->where('shipment_id', $shipment['id'])
                            ->where('isConfirmed', 0)
                            ->order_by('id', 'asc')
                            ->get_all();

                        if ($revised) {
                            $shipments = array_merge($shipments, $revised);
                        }
                    }
                }

                if ($shipments){
                    foreach ( array_reverse($shipments) as $shipment ) {
                        if ($shipment['isConfirmed'] || !empty($shipment['isReturn'])) {
                            foreach ($shipment['expirations'] as $sitem) {
                                foreach ($purchase['items'] as $pkey => $pitem) {
                                    if ($sitem['product_id'] == $pitem['product_id']) {
                                        if (!isset($purchase['items'][$pkey]['shipping_qty'])){
                                            $purchase['items'][$pkey]['shipping_qty'] = 0;
                                        }
                                        if (!empty($shipment['isReturn'])){
                                            $purchase['items'][$pkey]['shipping_qty'] -= $sitem['qty'];
                                        } else {
                                            $purchase['items'][$pkey]['shipping_qty'] += $sitem['qty'];
                                        }
                                    }
                                }
                            }

                            if (empty($shipment['isReturn'])) {
                                break;
                            }
                        }
                    }
                }
            }
        }

        $data = [
            'purchase' => $purchase,
            'shipments' => $shipments,
            'allowance_payments' => $allowance_payments,
            'total_allowance_payment' => $total_allowance_payment,
            'title' => '進貨單詳細資料',
            'view' => 'supervisor/detail',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/views/layout/login.php
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="designer" content="cystudio, <EMAIL>" />
    <title><?= $title ?></title>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
            integrity="<KEY>"
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-M5LQ7CP');</script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
            integrity="<KEY>"
            crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="<KEY>" crossorigin="anonymous">
    <link href="<?= base_url('css/styles.css') ?>" rel="stylesheet" type="text/css">
    <style>
        html, body {
            background-color: #9BBB59;
        }
    </style>
</head>

<body>
<?php if (!empty($msg)) { ?>
    <div class="container">
        <div class="alert alert-info alert-dismissible">
            <?= $msg ?>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    </div>
<?php } ?>

<?php
if (isset($data)) {
    $this->load->view($view, $data);
} else {
    $this->load->view($view);
}
?>
</body>
</html>

<file_sep>/application/views/guest/info.php
<div class="container">
    <h1 class="mb-4 text-center">經銷商基本資料</h1>

    <form method="post" id="orderForm">
        <?php if (validation_errors()){ ?>
            <div class="alert alert-danger">
                <?=validation_errors()?>
            </div>
        <?php } ?>

        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <td>經銷商名稱</td>
                <td colspan="3">
                        <input name="company" class="form-control" maxlength="20" required
                               value="<?= set_value('company', $guest['retailer']['company']) ?>">
                </td>
            </tr>
            <tr>
                <td>身份證字號/統一編號</td>
                <td colspan="3">
                        <input name="identity" class="form-control" maxlength="10" required
                               value="<?= set_value('identity', $guest['retailer']['identity']) ?>">
                </td>
            </tr>
            <tr>
                <td>經銷商類別</td>
                <td colspan="3">
                    <?= $guest['level']['title'] ?>
                </td>
            </tr>
            <tr>
                <td>進貨折扣</td>
                <td colspan="3">
                    <?= $guest['level']['discount'] . '%'?>
                </td>
            </tr>
            <tr>
                <td>經銷商帳號</td>
                <td colspan="3">
                    <input name="account" class="form-control" value="" required />
                </td>
            </tr>
            <tr>
                <td>登入密碼</td>
                <td>
                    <input type="<PASSWORD>" name="password" class="form-control" value="" />
                </td>
                <td>確認密碼</td>
                <td>
                    <input type="<PASSWORD>" name="password_confirm" class="form-control" value="" />
                </td>
            </tr>
            <tr>
                <th>輔銷人</th>
                <td><?= $guest['sales_dealer']['name'] ?></td>
                <th>輔銷人代號</th>
                <td><?= $guest['sales_dealer']['account'] ?></td>
            </tr>
            <tr>
                <th>輔銷單位</th>
                <td colspan="3"><?= $guest['sales_retailer']['company'] ?></td>
            </tr>
            <tr>
                <td>經銷商代表人姓名</td>
                <td>
                        <input name="contact" class="form-control" maxlength="20" required
                               value="<?= set_value('contact', $guest['retailer']['contact']) ?>">
                </td>
                <td>性別</td>
                <td>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="gender_1" value="1"<?= set_value('gender', $guest['retailer']['gender']) == '1' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="gender_1">男</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="gender_0" value="0"<?= set_value('gender', $guest['retailer']['gender']) === '0' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="gender_0">女</label>
                        </div>
                </td>
            </tr>
            <tr>
                <td>聯絡電話1</td>
                <td colspan="3">
                        <input name="phone" class="form-control" maxlength="20" required
                               value="<?= set_value('phone', $guest['retailer']['phone']) ?>">
                </td>
            </tr>
            <tr>
                <td>聯絡電話2</td>
                <td colspan="3">
                        <input name="altPhone" class="form-control" maxlength="20"
                               value="<?= set_value('altPhone', $guest['retailer']['altPhone']) ?>">
                </td>
            </tr>
            <tr>
                <td>送貨地址</td>
                <td colspan="3">
                    <input name="address" class="form-control" maxlength="100" required
                           value="<?= set_value('address', $guest['retailer']['address']) ?>">
                </td>
            </tr>
        </table>

        <h4 class="my-4 text-center">訂貨明細</h4>
        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <td>項次</td>
                <td>貨品編號</td>
                <td>貨品名稱</td>
                <td>分類</td>
                <td>單價</td>
                <td>訂購數量</td>
                <td>金額小計</td>
                <td>折扣</td>
                <td>折扣價</td>
            </tr>
            <?php
            if ($products) {
                $i = 1;
                foreach ($products as $pId => $product) {
                    ?>
                    <tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
                        <td data-th="項次" class="text-center"><?= $i ?></td>
                        <td data-th="貨品編號"><?= $product['p_num'] ?></td>
                        <td data-th="貨品名稱"><?= $product['name'] ?></td>
                        <td data-th="分類"><?= $product['ctName'] ?></td>
                        <td data-th="單價" class="text-right">$<?= number_format($product['price']) ?></td>
                        <td data-th="訂購數量" class="text-right"><?= number_format($product['qty']) ?></td>
                        <td data-th="金額小計" class="text-right">$<?= number_format($product['price'] * $product['qty']) ?></td>
                        <td data-th="折扣"
                            class="text-right"><?=$guest['level']['discount'] . '%' ?></td>
                        <td data-th="折扣價"
                            class="text-right">
                            $<?= number_format(floor($product['price'] * $guest['level']['discount'] / 100) * $product['qty']) ?></td>
                    </tr>
                    <?php
                    $i++;
                }
            }
            ?>
            <tr>
                <td colspan="6" class="text-right font-weight-bold">小計</td>
                <td class="text-right font-weight-bold">$<?= number_format($guest['purchase']['subtotal']) ?></td>
                <td class="text-right font-weight-bold">總計</td>
                <td class="text-right font-weight-bold">$<?= number_format($guest['purchase']['total']) ?></td>
            </tr>
            <tr>
                <td colspan="6" class="text-right">備註</td>
                <td colspan="3">
                    <textarea rows="4" name="memo" class="form-control"><?= $guest['purchase']['memo'] ?></textarea>
                </td>
            </tr>
        </table>

        <div class="form-group text-center">
            <input type="submit" name="cart" class="btn" value="回訂貨單" />
            <input type="submit" name="checkout" class="btn btn-success" value="確認資料並下單" />
        </div>
    </form>
</div>
<file_sep>/application/models/Retailer_role_model.php
<?php

class Retailer_role_model extends MY_Model
{
    public $table = 'olive_retailer_roles';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['retailers'] = array('Retailer_model', 'retailer_role_id', 'id');
        $this->has_many['groups'] = array('Retailer_group_model', 'retailer_role_id', 'id');
        $this->has_many['level_types'] = array('Retailer_level_type_model', 'retailer_role_id', 'id');
    }

    public function getRoleSelect()
    {
        $_roles = $this
            ->where('id', '!=', 5) //經銷商不能自行新增
            ->get_all();
        $roles = [];
        foreach ($_roles as $role){
            $roles[$role['id']] = $role['title'];
        }
        return $roles;
    }
}

?>
<file_sep>/application/models/Shipment_model.php
<?php

class Shipment_model extends MY_Model
{
    public $table = 'olive_shipments';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['shipout_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipout_retailer_id');
        $this->has_one['shipin_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipin_retailer_id');
        $this->has_many['items'] = array('Shipment_item_model', 'shipment_id', 'id');
        $this->has_many['expirations'] = array('Shipment_expiration_model', 'shipment_id', 'id');
        $this->has_one['revise'] = array('foreign_model' => 'Shipment_revise_model', 'foreign_table' => 'olive_shipment_revises', 'foreign_key' => 'shipment_id', 'local_key' => 'id');
        $this->has_one['confirm'] = array('foreign_model' => 'Confirm_model', 'foreign_table' => 'olive_confirms', 'foreign_key' => 'confirm_id', 'local_key' => 'id');
        $this->has_one['expense'] = array('foreign_model' => 'Expense_model', 'foreign_table' => 'olive_expenses', 'foreign_key' => 'event_id', 'local_key' => 'id');
        $this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'ship_id');
    }

    public function generateShipmentConfirmLabel($shipment, $showMemo = false)
    {
        $string = '';
        if (is_null($shipment['isConfirmed'])){
            $string .= '<span class="badge badge-warning">待確認</span>';
        } else {
            $confirm = $shipment['confirm'];
            if ($confirm) {
                $this->load->helper('data_format');
                $string .= confirmStatus($confirm['audit'], $confirm['memo']);
                if ($showMemo) {
                    $string .= '<div>' . $confirm['memo'] . '</div>';
                }
            }
        }

        return $string;
    }
}

?>
<file_sep>/application/views/income/overview.php
<div class="container">
    <h1 class="mb-4">營業資訊</h1>

    <form id="search_form">
        <div class="card mb-4">
            <div class="card-header">搜尋</div>
            <div class="card-body">
                <div class="form-row">
                    <div class="form-group col-md-3">
                        <label for="purchaseNum">單位</label>
                        <select name="retailer_id" class="form-control" required>
                            <option>本單位</option>
                            <?php foreach ($retailers as $retailer){ ?>
                                <option value="<?=$retailer['retailer_id']?>"<?php if ($search['retailer_id'] == $retailer['retailer_id']){ echo 'selected'; } ?>><?=$retailer['retailer']['company']?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="form-group col-md-3">
                        <label for="created_start">查詢日期起</label>
                        <input type="date" class="form-control" name="created_start" required value="<?=$search['created_start']?>" />
                    </div>
                    <div class="form-group col-md-3">
                        <label for="created_end">查詢日期訖</label>
                        <input type="date" class="form-control" name="created_end" required value="<?=$search['created_end']?>" />
                    </div>
                </div>
            </div>
            <div class="card-footer text-center">
                <input type="submit" value="搜尋" class="btn btn-primary" />
                <a href="<?=base_url('/income/overview')?>" class="btn btn-light">重設</a>
            </div>
        </div>
    </form>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">分錄</th>
            <th class="text-center">金額</th>
        </tr>
        <?php
        if ($income) {
            if ($income['revenue']){
                foreach ($income['revenue'] as $revenue) {
                    ?>
                    <tr>
                        <th class="text-left"><?= $revenue['name'] ?></th>
                        <td class="text-right">$ <?= number_format($revenue['total']) ?></td>
                    </tr>
                    <?php
                }
            }

            if ($income['expense']){
                foreach ($income['expense'] as $expense) {
                    ?>
                    <tr>
                        <th class="text-left"><?= $expense['name'] ?></th>
                        <td class="text-right">$ -<?= number_format($expense['total']) ?></td>
                    </tr>
                    <?php
                }
            }
            ?>
            <tr class="bg-light">
                <th class="text-left">毛利</th>
                <th class="text-right">$ <?= number_format($income['total']) ?></th>
            </tr>
            <?php
        } else {
            ?>
            <tr>
                <td colspan="2" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>
</div><file_sep>/application/models/Retailer_model.php
<?php

class Retailer_model extends MY_Model
{
    public $table = 'olive_retailers';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['dealers'] = array('Dealer_model', 'retailer_id', 'id');
        $this->has_one['contact_dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'contact_dealer_id');
        $this->has_one['level'] = array('foreign_model' => 'Retailer_level_model', 'foreign_table' => 'olive_retailer_levels', 'foreign_key' => 'id', 'local_key' => 'retailer_level_id');
        $this->has_one['role'] = array('foreign_model' => 'Retailer_role_model', 'foreign_table' => 'olive_retailer_roles', 'foreign_key' => 'id', 'local_key' => 'retailer_role_id');
        $this->has_many['relationships'] = array('Retailer_relationship_model', 'retailer_id', 'id');
        $this->has_one['sales_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'sales_retailer_id');
        $this->has_one['sales_dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'sales_dealer_id');
    }

    public function getRetailerSelect()
    {
        $_retailers = $this->get_all();
        $retailers = [];
        foreach ($_retailers as $retailer){
            $retailers[$retailer['id']] = $retailer['company'];
        }
        return $retailers;
    }

    public function getRetailerHasStock()
    {
        return $this
            ->where('hasStock', 1)
            ->where('totalStock', 1)
            ->order_by('retailer_role_id', 'asc')
            ->get_all();
    }
}

?>
<file_sep>/application/migrations/040_update_shipment.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_shipment extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_shipments', [
            'product_verify' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
                'after' => 'memo',
            ],
            'fare_verify' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
                'after' => 'product_verify',
            ],
            'shipment_verify' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
                'after' => 'fare_verify',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_shipments', 'product_verify');
        $this->dbforge->drop_column('olive_shipments', 'fare_verify');
        $this->dbforge->drop_column('olive_shipments', 'shipment_verify');
    }
}<file_sep>/application/models/Payment_model.php
<?php

class Payment_model extends MY_Model
{
    public $table = 'olive_payments';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['paid_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'paid_retailer_id');
        $this->has_one['received_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'received_retailer_id');
        $this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'pay_id');
        $this->has_one['confirm'] = array('foreign_model' => 'Confirm_model', 'foreign_table' => 'olive_confirms', 'foreign_key' => 'confirm_id', 'local_key' => 'id');
    }

    public function generatePaymentConfirmLabel($payment, $showMemo = false)
    {
        $string = '';
        if (is_null($payment['isConfirmed'])){
            $string .= '<span class="badge badge-warning">待確認</span>';
        } else {
            $confirm = $payment['confirm'];
            if ($confirm) {
                $string .= confirmStatus($confirm['audit'], $confirm['memo'], '確認已收款');
                if ($showMemo) {
                    $string .= '<div>' . $confirm['memo'] . '</div>';
                }
            }
        }

        return $string;
    }
}

?>
<file_sep>/application/views/capital/relationship/invoice/edit.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">編輯<?= $relationship['retailer']['company'] ?> 發票關係單位</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label class="font-weight-bold">出貨單位</label>
                    <input class="form-control-plaintext" value="<?= $relationship['relation']['company'] ?>"/>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">發票單位</label>
                    <input class="form-control-plaintext" value="<?= $relationship['alter']['company'] ?>"/>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">折扣</label>
                    <div class="input-group">
                        <input type="number" name="discount" class="form-control text-right" max="100" min="1" value="<?= set_value('discount', $relationship['discount']) ?>"/>
                        <div class="input-group-append">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/capital_relationship_invoice/overview/' . $relationship['retailer_id'])?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="更新"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/controllers/Capital_customer_level.php
<?php

class Capital_customer_level extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('customer_level_model');

        $this->session->set_userdata('return_page', base_url('/capital_customer_level/overview'));
    }

    public function overview()
    {
        $levels = $this->customer_level_model
            ->with_type()
            ->get_all();

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_customer_level', 'edit')){
            $authority['edit'] = true;
        }

        $data = [
            'levels' => $levels,
            'authority' => $authority,
            'title' => '會員資格管理',
            'view' => 'capital/customer_level/overview',
        ];

        $this->_preload($data);
    }

    public function edit($customer_level_id)
    {
        $level = $this->customer_level_model
            ->with_type()
            ->get($customer_level_id);

        if (!$customer_level_id || !$level) {
            show_error('查無會員資格資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('title', '名稱', 'required|max_length[10]');
            $this->form_validation->set_rules('discount', '折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');

            if ($this->form_validation->run() !== FALSE) {
                $update_data = [
                    'title' => $this->input->post('title'),
                    'discount' => $this->input->post('discount'),
                    'description' => $this->input->post('description'),
                ];
                $this->customer_level_model->update($update_data, ['id' => $customer_level_id]);

                redirect(base_url('/capital_customer_level/overview/'));
            }
        }

        $data = [
            'level' => $level,
            'title' => '編輯會員資格管理',
            'view' => 'capital/customer_level/edit',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/controllers/Seeder.php
<?php
class Seeder extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        if (!$this->input->is_cli_request()) {
            show_error('你沒有權限使用');
        }

    }

    public function all()
    {
        $this->retailer_role();
        $this->retailer_level_type();
        $this->retailer_level();
        $this->retailer_group();
        $this->retailer();
        $this->retailer_relationship();
        $this->privilege();
        $this->customer_level();

        $this->db->truncate('olive_commissions');
        $this->db->truncate('olive_combos');
        $this->db->truncate('olive_combo_items');
        $this->db->truncate('olive_confirms');
        $this->db->truncate('olive_coupons');
        $this->db->truncate('olive_coupon_approves');
        $this->db->truncate('olive_customers');
        $this->db->truncate('olive_customer_level_histories');
        $this->db->truncate('olive_expenses');
        $this->db->truncate('olive_free_package_items');
        $this->db->truncate('olive_old_customers');
        $this->db->truncate('olive_orders');
        $this->db->truncate('olive_order_contacts');
        $this->db->truncate('olive_order_items');
        $this->db->truncate('olive_order_returns');
        $this->db->truncate('olive_order_recipients');
        $this->db->truncate('olive_payments');
        $this->db->truncate('olive_purchases');
        $this->db->truncate('olive_promotes');
        $this->db->truncate('olive_promote_items');
        $this->db->truncate('olive_purchase_items');
        $this->db->truncate('olive_recommends');
        $this->db->truncate('olive_recommend_templates');
        $this->db->truncate('olive_shipments');
        $this->db->truncate('olive_shipment_items');
        $this->db->truncate('olive_stocks');
        $this->db->truncate('olive_stock_countings');
        $this->db->truncate('olive_stock_counting_items');

        echo 'Seeder 成功';
    }

    public function retailer_role()
    {
        $this->db->truncate('olive_retailer_roles');

        $this->load->model('retailer_role_model');
        $roles = [
            [
                'title' => '總代理',
                'account_prefix' => 'ZZ',
            ],
            [
                'title' => '總經銷',
                'account_prefix' => 'XX',
            ],
            [
                'title' => '皮瑪斯門市',
                'account_prefix' => 'YY',
            ],
            [
                'title' => '總代理門市與總代理百貨專櫃',
                'account_prefix' => 'SS',
            ],
            [
                'title' => '經銷商',
            ],
        ];
        foreach ($roles as $role) {
            $this->retailer_role_model->insert($role);
        }
    }

    public function retailer_level_type()
    {
        $this->db->truncate('olive_retailer_level_types');

        $this->load->model('retailer_level_type_model');
        $roles = [
            [
                'retailer_role_id' => 5,
                'type' => 'A',
                'title' => '個人經銷商',
                'description' => '<table class="table table-bordered"> <tbody> <tr> <td>&nbsp;</td> <td>經銷商類別</td> <td>代碼</td> <td>進貨折數</td> <td>首次進貨門檻</td> <td>每月進貨門檻</td> <td>裝修費(櫃體&amp;形象)</td> <td>保證金</td> <td>輔銷人輔導金(經銷商)</td> <td>輔銷人輔導金(總經銷人員或股東)</td> <td>輔銷人輔導金(皮瑪斯門市人員或股東)</td> </tr> <tr> <td rowspan="3">個人經銷商</td> <td>經銷人A</td> <td>AA</td> <td>定價80%</td> <td>2萬</td> <td>0.5萬/月</td> <td rowspan="3">-</td> <td rowspan="3">0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>經銷人Ｂ</td> <td>AB</td> <td>定價60%</td> <td>35萬</td> <td>3萬/月</td> <td>3%</td> <td>3%</td> <td>3%</td> </tr> <tr> <td>經銷人C</td> <td>AC</td> <td>定價60%</td> <td>20萬</td> <td>5萬/月</td> <td>3%</td> <td>3%</td> <td>3%</td> </tr> </tbody></table>',
            ],
            [
                'retailer_role_id' => 5,
                'type' => 'B',
                'title' => '櫃位經銷商',
                'description' => '<table class="table table-bordered"> <tbody> <tr> <td>&nbsp;</td> <td>經銷商類別</td> <td>代碼</td> <td>進貨折數</td> <td>首次進貨門檻</td> <td>每月進貨門檻</td> <td>裝修費(櫃體&amp;形象)</td> <td>保證金</td> <td>輔銷人輔導金(經銷商)</td> <td>輔銷人輔導金(總經銷人員或股東)</td> <td>輔銷人輔導金(皮瑪斯門市人員或股東)</td> </tr> <tr> <td rowspan="3">櫃位經銷商</td> <td>經銷櫃位Ａ</td> <td>BA</td> <td>定價60%</td> <td>35萬</td> <td>3萬/月</td> <td rowspan="3">每一櫃子 5-8 萬/小招 3-5 萬<br> /直招及帆布各 4–8 萬<br> /輸出 5-10 萬<br> /教育訓練費 3 萬<br> (若參與皮革護理業務再加 5 萬)<br> /飾品 1 萬/裝修費工料另訂</td> <td rowspan="3">5萬</td> <td>3%</td> <td>3%</td> <td>3%</td> </tr> <tr> <td>經銷櫃位Ｂ</td> <td>BB</td> <td>定價55%</td> <td>55萬</td> <td>10萬/月</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> <tr> <td>經銷櫃位C</td> <td>BC</td> <td>定價47%</td> <td>90萬</td> <td>10萬/月</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> </tbody></table>',
            ],
            [
                'retailer_role_id' => 5,
                'type' => 'C',
                'title' => '店面經銷商',
                'description' => '<table class="table table-bordered"> <tbody> <tr> <td>&nbsp;</td> <td>經銷商類別</td> <td>代碼</td> <td>進貨折數</td> <td>首次進貨門檻</td> <td>每月進貨門檻</td> <td>裝修費(櫃體&amp;形象)</td> <td>保證金</td> <td>輔銷人輔導金(經銷商)</td> <td>輔銷人輔導金(總經銷人員或股東)</td> <td>輔銷人輔導金(皮瑪斯門市人員或股東)</td> </tr> <tr> <td rowspan="4">店面經銷商:<br/>經銷店面之特定資訊於整體宣傳上之媒介： 名片 店卡 型錄 提袋 官網 臉書 IG 免費服務專線</td> <td>經銷店面Ａ</td> <td>CA</td> <td>定價55%</td> <td>55萬</td> <td>10萬/月</td> <td>160萬(室內12坪內)</td> <td rowspan="4">5萬</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> <tr> <td>經銷店面Ｂ</td> <td>CB</td> <td>定價55%</td> <td>55萬</td> <td>10萬/月</td> <td>190萬(室內12-20坪內)</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> <tr> <td>經銷店面Ｃ</td> <td>CC</td> <td>定價55%</td> <td>55萬</td> <td>10萬/月</td> <td>220萬(室內20-35坪內)</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> <tr> <td>經銷店面Ｄ</td> <td>CD</td> <td>定價55%</td> <td>55萬</td> <td>10萬/月</td> <td>250萬(室內35-50坪內)</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> </tbody></table>',
            ],
        ];
        foreach ($roles as $role) {
            $this->retailer_level_type_model->insert($role);
        }
    }

    public function retailer_level()
    {
        $this->db->truncate('olive_retailer_levels');

        $this->load->model('retailer_level_model');
        $levels = [
            [
                'discount' => 80,
                'retailer_level_type_id' => 1,
                'code' => 'A',
                'firstThreshold' => '20000',
                'monthThreshold' => '5000',
            ],
            [
                'discount' => 60,
                'retailer_level_type_id' => 1,
                'code' => 'B',
                'firstThreshold' => '350000',
                'monthThreshold' => '30000',
            ],
            [
                'discount' => 60,
                'retailer_level_type_id' => 1,
                'code' => 'C',
                'firstThreshold' => '200000',
                'monthThreshold' => '50000',
            ],
            [
                'discount' => 60,
                'retailer_level_type_id' => 2,
                'code' => 'A',
                'firstThreshold' => '350000',
                'monthThreshold' => '30000',
            ],
            [
                'discount' => 55,
                'retailer_level_type_id' => 2,
                'code' => 'B',
                'firstThreshold' => '550000',
                'monthThreshold' => '100000',
            ],
            [
                'discount' => 47,
                'retailer_level_type_id' => 2,
                'code' => 'C',
                'firstThreshold' => '900000',
                'monthThreshold' => '100000',
            ],
            [
                'discount' => 55,
                'retailer_level_type_id' => 3,
                'code' => 'A',
                'firstThreshold' => '550000',
                'monthThreshold' => '100000',
            ],
            [
                'discount' => 55,
                'retailer_level_type_id' => 3,
                'code' => 'B',
                'firstThreshold' => '550000',
                'monthThreshold' => '100000',
            ],
            [
                'discount' => 55,
                'retailer_level_type_id' => 3,
                'code' => 'C',
                'firstThreshold' => '550000',
                'monthThreshold' => '100000',
            ],
            [
                'discount' => 55,
                'retailer_level_type_id' => 3,
                'code' => 'D',
                'firstThreshold' => '550000',
                'monthThreshold' => '100000',
            ],
        ];

        foreach ($levels as $level) {
            $this->retailer_level_model->insert($level);
        }
    }


    public function retailer_group()
    {
        $this->db->truncate('olive_retailer_groups');

        $this->load->model('retailer_group_model');
        $levels = [
            [
                'retailer_role_id' => 1, //總代理
                'retailer_level_type_id' => null,
                'title' => '徐總',
            ],
            [
                'retailer_role_id' => 1,
                'retailer_level_type_id' => null,
                'title' => '秘書長',
            ],
            [
                'retailer_role_id' => 1,
                'retailer_level_type_id' => null,
                'title' => '品牌設計',
            ],
            [
                'retailer_role_id' => 2, //總經銷 4
                'retailer_level_type_id' => null,
                'title' => '總監',
            ],
            [
                'retailer_role_id' => 2,
                'retailer_level_type_id' => null,
                'title' => '董事',
            ],
            [
                'retailer_role_id' => 2,
                'retailer_level_type_id' => null,
                'title' => '行政主任',
            ],
            [
                'retailer_role_id' => 3, //門市 7
                'retailer_level_type_id' => null,
                'title' => '股東',
            ],
            [
                'retailer_role_id' => 3,
                'retailer_level_type_id' => null,
                'title' => '店長',
            ],
            [
                'retailer_role_id' => 3,
                'retailer_level_type_id' => null,
                'title' => '副店長',
            ],
            [
                'retailer_role_id' => 3,
                'retailer_level_type_id' => null,
                'title' => '營業員',
            ],
            [
                'retailer_role_id' => 4, //百貨 11
                'retailer_level_type_id' => null,
                'title' => '店長',
            ],
            [
                'retailer_role_id' => 4,
                'retailer_level_type_id' => null,
                'title' => '副店長',
            ],
            [
                'retailer_role_id' => 4,
                'retailer_level_type_id' => null,
                'title' => '營業員',
            ],
            [
                'retailer_role_id' => 5, //個人經銷商 14
                'retailer_level_type_id' => 1,
                'title' => '個人經銷商',
            ],
            [
                'retailer_role_id' => 5, //櫃位經銷商 15
                'retailer_level_type_id' => 2,
                'title' => '負責人',
            ],
            [
                'retailer_role_id' => 5,
                'retailer_level_type_id' => 2,
                'title' => '營業員',
            ],
            [
                'retailer_role_id' => 5, //店面經銷商 17
                'retailer_level_type_id' => 3,
                'title' => '店東',
            ],
            [
                'retailer_role_id' => 5,
                'retailer_level_type_id' => 3,
                'title' => '店長',
            ],
            [
                'retailer_role_id' => 5,
                'retailer_level_type_id' => 3,
                'title' => '副店長',
            ],
            [
                'retailer_role_id' => 5,
                'retailer_level_type_id' => 3,
                'title' => '營業員',
            ],
        ];

        foreach ($levels as $level) {
            $this->retailer_group_model->insert($level);
        }
    }

    public function retailer()
    {
        $this->db->truncate('olive_dealers');
        $this->db->truncate('olive_retailers');

        //seeder default 總經銷
        $this->load->model('dealer_model');
        $this->load->model('retailer_model');

        $retailer_id = $this->retailer_model->insert([
            'retailer_role_id' => 1,
            'serialNum' => '00001',
            'companyNum' => 'ZZ00001',
            'company' => '總代理',
            'eta_days' => 60,
            'hasStock' => 1,
            'isLocked' => 1,
        ]);

        $dealer_id = $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 1,
            'account' => 'ZZ00001',
            'password' => $this->authentic->_mix('password'),
            'name' => '徐總',
            'isLocked' => 1,
        ]);

        $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);

        $retailer_id = $this->retailer_model->insert([
            'retailer_role_id' => 2,
            'serialNum' => '00001',
            'companyNum' => 'XX00001',
            'company' => '華利國際有限公司',
            'invoice_title' => '華利國際有限公司',
            'address' => '台中市西屯區台灣大道二段812號二樓',
            'purchaseThreshold' => 10000,
            'hasStock' => 1,
            'totalStock' => 1,
            'eta_days' => 15,
            'isLocked' => 1,
        ]);

        $dealer_id = $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 4,
            'account' => 'YY00001',
            'password' => $this->authentic->_mix('password'),
            'name' => '總監',
            'isLocked' => 1,
        ]);

        $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);

        $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 4,
            'account' => 'mark',
            'password' => $this->authentic->_mix('<PASSWORD>'),
            'name' => 'Mark',
            'isLocked' => 1,
        ]);

        $retailer_id = $this->retailer_model->insert([
            'retailer_role_id' => 3,
            'serialNum' => '00002',
            'companyNum' => 'XX00002',
            'company' => '皮瑪斯台北忠孝門市',
            'invoice_title' => '實現潔淨保養名鋪',
            'address' => '台北市忠孝東路四段101巷25號',
            'purchaseThreshold' => 10000,
            'hasStock' => 1,
            'totalStock' => 1,
            'eta_days' => 15,
            'isLocked' => 1,
        ]);

        $dealer_id = $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 8,
            'account' => 'YY00002',
            'password' => $this->authentic->_mix('password'),
            'name' => '皮瑪斯台北店長',
            'isLocked' => 1,
        ]);

        $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);

        $retailer_id = $this->retailer_model->insert([
            'retailer_role_id' => 3,
            'serialNum' => '00003',
            'companyNum' => 'XX00003',
            'company' => '皮瑪斯新竹西大門市',
            'invoice_title' => '永遠潔淨保養名鋪',
            'address' => '新竹市東區西大路107號一樓',
            'purchaseThreshold' => 10000,
            'hasStock' => 1,
            'totalStock' => 1,
            'eta_days' => 15,
            'isLocked' => 1,
        ]);

        $dealer_id = $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 8,
            'account' => 'YY00003',
            'password' => $this->authentic->_mix('password'),
            'name' => '皮瑪斯新竹店長',
            'isLocked' => 1,
        ]);

        $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);

        $retailer_id = $this->retailer_model->insert([
            'retailer_role_id' => 3,
            'serialNum' => '00004',
            'companyNum' => 'XX00004',
            'company' => '皮瑪斯台中台灣大道門市',
            'invoice_title' => '堅定潔淨保養名鋪',
            'address' => '台中市台灣大道二段812號一樓',
            'purchaseThreshold' => 10000,
            'hasStock' => 1,
            'totalStock' => 1,
            'eta_days' => 15,
            'isLocked' => 1,
        ]);

        $dealer_id = $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 8,
            'account' => 'YY00004',
            'password' => $this->authentic->_mix('password'),
            'name' => '皮瑪斯台中店長',
            'isLocked' => 1,
        ]);

        $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);

        $retailer_id = $this->retailer_model->insert([
            'retailer_role_id' => 3,
            'serialNum' => '00005',
            'companyNum' => 'XX00005',
            'company' => '皮瑪斯台南永華門市',
            'invoice_title' => '繁榮潔淨保養名鋪',
            'address' => '台南市中西區永華路一段72號一樓',
            'purchaseThreshold' => 10000,
            'hasStock' => 1,
            'totalStock' => 1,
            'eta_days' => 15,
            'isLocked' => 1,
        ]);

        $dealer_id = $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 8,
            'account' => 'YY00005',
            'password' => $this->authentic->_mix('<PASSWORD>'),
            'name' => '皮瑪斯台南店長',
            'isLocked' => 1,
        ]);

        $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);

        $retailer_id = $this->retailer_model->insert([
            'retailer_role_id' => 3,
            'serialNum' => '00006',
            'companyNum' => 'XX00006',
            'company' => '皮瑪斯高雄中華五福門市',
            'invoice_title' => '幸福潔淨保養名鋪',
            'address' => '高雄市前金區中華四路351號一樓',
            'purchaseThreshold' => 10000,
            'hasStock' => 1,
            'totalStock' => 1,
            'eta_days' => 15,
            'isLocked' => 1,
        ]);

        $dealer_id = $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 8,
            'account' => 'YY00006',
            'password' => $this->authentic->_mix('password'),
            'name' => '皮瑪斯高雄店長',
            'isLocked' => 1,
        ]);

        $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);

        $retailer_id = $this->retailer_model->insert([
            'retailer_role_id' => 4,
            'serialNum' => '00001',
            'companyNum' => 'SS00001',
            'company' => '新北淡水門市',
            'invoice_title' => '新北淡水門市',
            'address' => ' 新北市中正路72-1號',
            'purchaseThreshold' => 10000,
            'hasStock' => 1,
            'eta_days' => 15,
        ]);

        $dealer_id = $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 11,
            'account' => 'SS00001',
            'password' => $this->authentic->_mix('password'),
            'name' => '新北淡水門市店長',
        ]);

        $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);

        $retailer_id = $this->retailer_model->insert([
            'retailer_role_id' => 4,
            'serialNum' => '00002',
            'companyNum' => 'SS00002',
            'company' => '台北大葉高島屋專櫃',
            'invoice_title' => '台北大葉高島屋專櫃',
            'address' => ' 台北市忠誠路2段55號大葉高島屋1F',
            'purchaseThreshold' => 10000,
            'hasStock' => 1,
            'eta_days' => 15,
        ]);

        $dealer_id = $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 11,
            'account' => 'SS00002',
            'password' => $this->authentic->_mix('password'),
            'name' => '台北大葉高島屋專櫃店長',
        ]);

        $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);

        $retailer_id = $this->retailer_model->insert([
            'retailer_role_id' => 4,
            'serialNum' => '00003',
            'companyNum' => 'SS00003',
            'company' => '新竹巨城百貨專櫃',
            'invoice_title' => '新竹巨城百貨專櫃',
            'address' => '新竹市中央路229號巨城百貨3F',
            'purchaseThreshold' => 10000,
            'hasStock' => 1,
            'eta_days' => 15,
        ]);

        $dealer_id = $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 11,
            'account' => 'SS00003',
            'password' => $this->authentic->_mix('password'),
            'name' => '新竹巨城百貨專櫃店長',
        ]);

        $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);

        $retailer_id = $this->retailer_model->insert([
            'retailer_role_id' => 4,
            'serialNum' => '00004',
            'companyNum' => 'SS00004',
            'company' => '臺中金典綠園道專櫃',
            'invoice_title' => '臺中金典綠園道專櫃',
            'address' => '台中市健行路1049號金典綠園道1F',
            'purchaseThreshold' => 10000,
            'hasStock' => 1,
            'eta_days' => 15,
        ]);

        $dealer_id = $this->dealer_model->insert([
            'retailer_id' => $retailer_id,
            'retailer_group_id' => 11,
            'account' => 'SS00004',
            'password' => $this->authentic->_mix('<PASSWORD>'),
            'name' => '臺中金典綠園道專櫃店長',
        ]);

        $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
    }

    public function retailer_relationship()
    {
        $this->db->truncate('olive_retailer_relationships');

        $this->load->model('retailer_relationship_model');
        $relationships = [
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 8,
//                'relation_retailer_id' => 1,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 9,
//                'relation_retailer_id' => 1,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 10,
//                'relation_retailer_id' => 1,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 11,
//                'relation_retailer_id' => 1,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 3,
//                'relation_retailer_id' => 2,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 4,
//                'relation_retailer_id' => 2,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 5,
//                'relation_retailer_id' => 2,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 6,
//                'relation_retailer_id' => 2,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 7,
//                'relation_retailer_id' => 2,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 8,
//                'relation_retailer_id' => 2,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 9,
//                'relation_retailer_id' => 2,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 10,
//                'relation_retailer_id' => 2,
//            ],
//            [
//                'relation_type' => 'supervisor',
//                'retailer_id' => 11,
//                'relation_retailer_id' => 2,
//            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'discount' => 45,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 3,
                'relation_retailer_id' => 2,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 4,
                'relation_retailer_id' => 2,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 5,
                'relation_retailer_id' => 2,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 6,
                'relation_retailer_id' => 2,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 7,
                'relation_retailer_id' => 2,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 8,
                'relation_retailer_id' => 1,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 9,
                'relation_retailer_id' => 1,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 10,
                'relation_retailer_id' => 1,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipout',
                'retailer_id' => 11,
                'relation_retailer_id' => 1,
                'discount' => 55,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 3,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 4,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 5,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 6,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 7,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
                'alter_retailer_id' => 4,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
                'alter_retailer_id' => 5,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
                'alter_retailer_id' => 6,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
                'alter_retailer_id' => 7,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
                'alter_retailer_id' => 3,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
                'alter_retailer_id' => 5,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
                'alter_retailer_id' => 6,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
                'alter_retailer_id' => 7,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
                'alter_retailer_id' => 3,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
                'alter_retailer_id' => 4,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
                'alter_retailer_id' => 6,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
                'alter_retailer_id' => 7,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
                'alter_retailer_id' => 3,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
                'alter_retailer_id' => 4,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
                'alter_retailer_id' => 5,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
                'alter_retailer_id' => 7,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
                'alter_retailer_id' => 3,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
                'alter_retailer_id' => 4,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
                'alter_retailer_id' => 5,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
                'alter_retailer_id' => 6,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 3,
                'relation_retailer_id' => 2,
                'alter_retailer_id' => 3,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 4,
                'relation_retailer_id' => 2,
                'alter_retailer_id' => 4,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 5,
                'relation_retailer_id' => 2,
                'alter_retailer_id' => 5,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 6,
                'relation_retailer_id' => 2,
                'alter_retailer_id' => 6,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 7,
                'relation_retailer_id' => 2,
                'alter_retailer_id' => 7,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 8,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 8,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 9,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 9,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 10,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 10,
            ],
            [
                'relation_type' => 'shipin',
                'retailer_id' => 11,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 11,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 3,
                'discount' => 42,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
                'alter_retailer_id' => 4,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
                'alter_retailer_id' => 5,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
                'alter_retailer_id' => 6,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
                'alter_retailer_id' => 7,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 4,
                'discount' => 42,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
                'alter_retailer_id' => 3,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
                'alter_retailer_id' => 5,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
                'alter_retailer_id' => 6,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
                'alter_retailer_id' => 7,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 5,
                'discount' => 42,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
                'alter_retailer_id' => 3,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
                'alter_retailer_id' => 4,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
                'alter_retailer_id' => 6,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
                'alter_retailer_id' => 7,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 6,
                'discount' => 42,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
                'alter_retailer_id' => 3,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
                'alter_retailer_id' => 4,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
                'alter_retailer_id' => 5,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
                'alter_retailer_id' => 7,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 7,
                'discount' => 42,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
                'alter_retailer_id' => 2,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
                'alter_retailer_id' => 3,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
                'alter_retailer_id' => 4,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
                'alter_retailer_id' => 5,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
                'alter_retailer_id' => 6,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 2,
                'relation_retailer_id' => 2,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 2,
                'relation_retailer_id' => 3,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 2,
                'relation_retailer_id' => 4,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 2,
                'relation_retailer_id' => 5,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 2,
                'relation_retailer_id' => 6,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 2,
                'relation_retailer_id' => 7,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 3,
                'relation_retailer_id' => 2,
                'alter_retailer_id' => 3,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 3,
                'relation_retailer_id' => 3,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 4,
                'relation_retailer_id' => 2,
                'alter_retailer_id' => 4,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 4,
                'relation_retailer_id' => 4,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 5,
                'relation_retailer_id' => 2,
                'alter_retailer_id' => 5,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 5,
                'relation_retailer_id' => 5,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 6,
                'relation_retailer_id' => 2,
                'alter_retailer_id' => 6,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 6,
                'relation_retailer_id' => 6,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 7,
                'relation_retailer_id' => 2,
                'alter_retailer_id' => 7,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 7,
                'relation_retailer_id' => 7,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 8,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 8,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 9,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 9,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 10,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 10,
            ],
            [
                'relation_type' => 'invoice',
                'retailer_id' => 11,
                'relation_retailer_id' => 1,
                'alter_retailer_id' => 11,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 8,
                'relation_retailer_id' => 8,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 9,
                'relation_retailer_id' => 9,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 10,
                'relation_retailer_id' => 10,
            ],
            [
                'relation_type' => 'invoice_send',
                'retailer_id' => 11,
                'relation_retailer_id' => 11,
            ],
        ];
        foreach ($relationships as $relationship) {
            $this->retailer_relationship_model->insert($relationship);
        }
    }

    public function privilege()
    {
        $this->db->truncate('olive_privileges');

        $this->load->model('privilege_model');
        $privileges = [
            [
                'classname' => 'capital_dealer',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_dealer',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_dealer',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_dealer',
                'methodname' => 'cancel',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_level',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_level',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_level',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_level_type',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_level_type',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_customer_level',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_customer_level',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_privilege',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_privilege',
                'methodname' => 'apps',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_privilege',
                'methodname' => 'authority',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_relationship_invoice',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_relationship_invoice',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_relationship_invoice_send',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_relationship_shipin',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_relationship_shipout',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_relationship_shipout',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_retailer',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_retailer',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_retailer',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_retailer',
                'methodname' => 'cancel',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_retailer_group',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_retailer_group',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_retailer_group',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_retailer_role',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_combo',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_combo',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_combo',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_combo',
                'methodname' => 'cancel',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_combo',
                'methodname' => 'check_total',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_free_package',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_free_package',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_free_package',
                'methodname' => 'cancel',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_free_package',
                'methodname' => 'check_duplicate',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_promote',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_promote',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_promote',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_promote',
                'methodname' => 'advance',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_promote',
                'methodname' => 'cancel',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'capital_stock',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'stock',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'stock',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 0, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'stock_counting',
                'methodname' => 'index',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'stock_counting',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'stock_counting',
                'methodname' => 'detail',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'stock_counting',
                'methodname' => 'set_print',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'stock_counting',
                'methodname' => 'process_print',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'stock_counting',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'stock_counting',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'guest',
                'methodname' => 'cart',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'guest',
                'methodname' => 'check_total',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'guest',
                'methodname' => 'adminCheck',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'guest',
                'methodname' => 'check_authentic',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'guest',
                'methodname' => 'info',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'purchase',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'purchase',
                'methodname' => 'detail',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'purchase',
                'methodname' => 'detail2',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 0, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'purchase',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'purchase',
                'methodname' => 'check_total',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'purchase',
                'methodname' => 'cancel',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'purchase',
                'methodname' => 'import_edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'purchase',
                'methodname' => 'import_confirm_supple',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'purchase',
                'methodname' => 'import_confirm_refund',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'purchase',
                'methodname' => 'import_return',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'transfer',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'transfer',
                'methodname' => 'transfer',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'transfer',
                'methodname' => 'detail',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'transfer',
                'methodname' => 'detail2',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 0, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'transfer',
                'methodname' => 'confirm',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'transfer',
                'methodname' => 'export_response',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'transfer',
                'methodname' => 'export_method_supple',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'transfer',
                'methodname' => 'export_method_refund',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'transfer',
                'methodname' => 'export_return_confirm',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'payment',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'payment',
                'methodname' => 'purchase',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'payment',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'payment',
                'methodname' => 'confirms',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'payment',
                'methodname' => 'confirm',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'payment',
                'methodname' => 'cancel',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'shipment',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'shipment',
                'methodname' => 'detail',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'shipment',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'shipment',
                'methodname' => 'confirm',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'shipment',
                'methodname' => 'check_qty',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'shipment',
                'methodname' => 'cancel',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'commission',
                'methodname' => 'dealers',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 0, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'commission',
                'methodname' => 'dealer',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 0, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'confirm',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'income',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'income',
                'methodname' => 'product',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'customer',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'customer',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'customer',
                'methodname' => 'consumer',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'customer',
                'methodname' => 'upgrade',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'customer',
                'methodname' => 'old',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'customer',
                'methodname' => 'old_detail',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'customer',
                'methodname' => 'conv_old',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'customer',
                'methodname' => 'active_old',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'customer',
                'methodname' => 'import',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'index',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'detail',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'check_qty',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'check_coupon',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'cancel',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'old',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'check_oldphone',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'trashed',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'recover',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'payAtShipped',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'shipping',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'paying',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'reject',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'consumer',
                'methodname' => 'orderReturn',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'coupon',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'coupon',
                'methodname' => 'detail',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'coupon',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'coupon',
                'methodname' => 'confirm',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'coupon',
                'methodname' => 'approved',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 0, //門市店長
                    11 => 0, //百貨店長
                    14 => 0, //個人經銷商
                    15 => 0, //櫃位經銷商負責人
                    17 => 0, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend',
                'methodname' => 'temp',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend',
                'methodname' => 'print_recommend',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend_template',
                'methodname' => 'index',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend_template',
                'methodname' => 'confirm',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend_template',
                'methodname' => 'confirm_edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend_template',
                'methodname' => 'inside',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend_template',
                'methodname' => 'inside_add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend_template',
                'methodname' => 'inside_edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend_template',
                'methodname' => 'outside',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend_template',
                'methodname' => 'outside_add',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend_template',
                'methodname' => 'outside_edit',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'recommend_template',
                'methodname' => 'confirming',
                'rules' => serialize([
                    1 => 0, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'dealer',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'dealer',
                'methodname' => 'profile',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'dealer',
                'methodname' => 'password',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'dealer',
                'methodname' => 'check_password',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'retailer',
                'methodname' => 'overview',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 0, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'retailer',
                'methodname' => 'add',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'retailer',
                'methodname' => 'edit',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
            [
                'classname' => 'retailer',
                'methodname' => 'cancel',
                'rules' => serialize([
                    1 => 1, //總代理徐總
                    4 => 1, //總經銷總監
                    8 => 1, //門市店長
                    11 => 1, //百貨店長
                    14 => 1, //個人經銷商
                    15 => 1, //櫃位經銷商負責人
                    17 => 1, //店面經銷商店東
                ]),
            ],
        ];

        foreach ($privileges as $privilege) {
            $this->privilege_model->insert($privilege);
        }
    }

    public function customer_level()
    {
        $this->db->truncate('olive_customer_levels');

        //seeder default
        $this->load->model('customer_level_model');
        $levels = [
            [
                'discount' => 95,
                'title' => '飄雪白卡',
                'description' => '<p>會員福利：</p>
<p>消費享9.5折優惠。</p>
<p>資格取得：</p>
<p>一顆橄欖相關商品一次消費滿12,000元、或年度消費滿20,000元、或皮瑪斯會員，可申請飄雪白卡會員。</p>
<p>「年度」：每年8月1日至次年7月31日為一年度。</p>
',
            ],
            [
                'discount' => 90,
                'title' => '春水綠卡',
                'description' => '<p>會員福利：</p>
<p>消費享9折優惠。</p>
<p>資格取得：</p>
<p>白卡會員年度消費次數達6次以上即可自動升等為綠卡會員。</p>
<p>「年度」：每年8月1日至次年7月31日為一年度。</p>
',
            ],
            [
                'discount' => 88,
                'title' => '曜石黑卡',
                'description' => '<p>會員福利：</p>
<p>1.一顆橄欖全系列商品享定價8.8折優惠。</p>
<p>2.免費使用一顆橄欖新品發表試用品。</p>
<p>3.免費參加年度感恩餐會。</p>
<p>4.享年度南法普羅旺斯免費住宿3天2夜(含莊園體驗及2食2泊招待，不含機票及交通)。</p>
<p>資格取得：</p>
<p>年度消費次數達20次以上、且消費金額滿330,000元之綠卡會員，自動升級為黑卡會員。</p>
<p>「年度」：每年8月1日至次年7月31日為一年度。</p>
',
            ],
        ];

        foreach ($levels as $level) {
            $this->customer_level_model->insert($level);
        }
    }

    public function shipment_items_convert()
    {
        $this->load->model('shipment_model');
        $this->load->model('shipment_expiration_model');

        $shipments = $this->shipment_model
            ->with_items()
            ->get_all();

        if ($shipments){
            foreach ($shipments as $shipment){
                $products = [];
                if (!empty($shipment['items'])) {
                    foreach ($shipment['items'] as $item) {
                        if (!isset($products[$item['product_id']])) {
                            $products[$item['product_id']] = 0;
                        }

                        $products[$item['product_id']] += $item['qty'];
                    }

                    foreach ($products as $product_id => $q) {
                        $this->shipment_expiration_model->insert([
                            'shipment_id' => $shipment['id'],
                            'product_id' => $product_id,
                            'expired_at' => null,
                            'qty' => $q,
                        ]);
                    }
                }
            }
        }
    }
}
?><file_sep>/application/views/stock_counting/index.php
<div class="container">
    <div class="justify-content-md-center d-flex align-items-center" style="height: 75vh;">
        <?php if (!empty($authority['print'])){ ?>
        <a href="<?=base_url('/stock_counting/set_print')?>" class="btn btn-success mr-4">「盤點清冊」下載</a>
        <?php } ?>
        <?php if (!empty($authority['add'])){ ?>
        <a href="<?=base_url('/stock_counting/add')?>" class="btn btn-success mr-4">盤盈虧報表新增</a>
        <?php } ?>
        <?php if (!empty($authority['overview'])){ ?>
        <a href="<?=base_url('/stock_counting/overview')?>" class="btn btn-success">盤點歷史紀錄列表</a>
        <?php } ?>
    </div>
</div><file_sep>/application/views/consumer/add.php
<div class="container">
    <?php
    if (!$customer && !validation_errors()) {
    ?>
    <div class="justify-content-md-center d-flex align-items-center" style="height: 75vh;">
        <a href="#" class="btn btn-success mr-4" id="btn-firstTime" >消費者首次訂購</a>
        <a href="<?=base_url('/customer/overview')?>" class="btn btn-success">消費者非首次訂購</a>
    </div>
    <?php } ?>


    <div id="order_wrap" class="<?php if (!$customer && !validation_errors()) { echo 'd-none'; }?>">
        <h1 class="mb-4 text-center"><?=$headline?></h1>

        <form method="post" id="orderForm">
            <?php if (validation_errors()) { ?>
                <div class="alert alert-danger">
                    <?= validation_errors() ?>
                </div>
            <?php } ?>
            <div class="row justify-content-md-center">
                <div class="col-md-8">
                    <?php if ($isOld){ ?>
                        <div class="form-group">
                            <label class="font-weight-bold">舊有會員轉換說明</label>
                            <ul>
                                <li>舊有會員召回完成實名登記者即成為綠卡會員。</li>
                                <li>舊有會員一年消費未滿 12次或未單次購買12,000元於 實名登記完隔年降為飄雪白卡。</li>
                                <li>舊有會員達2年未消費，自動喪失會員資格。</li>
                            </ul>
                        </div>
                    <?php } ?>

                    <div id="customer_info">
                        <div class="form-group">
                            <label class="font-weight-bold">姓名*</label>
                            <input name="name" class="form-control"
                                   value="<?= set_value('name', isset($customer['name']) ? $customer['name'] : '') ?>"/>
                        </div>
                        <div class="form-group">
                            <label class="font-weight-bold">電話*</label>
                            <input name="phone" class="form-control"
                                   value="<?= set_value('phone', isset($customer['phone']) ? $customer['phone'] : '') ?>"/>
                        </div>
                        <div class="form-group">
                            <label class="font-weight-bold">聯絡地址*</label>
                            <input name="address" class="form-control"
                                   value="<?= set_value('address', isset($customer['address']) ? $customer['address'] : '') ?>"/>
                        </div>
                        <div class="form-group">
                            <label class="font-weight-bold">收貨地址</label>
                            <input name="altAddress" class="form-control" value="<?= set_value('altAddress') ?>"/>
                        </div>
                        <div class="form-group">
                            <label class="font-weight-bold">性別</label>
                            <div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="gender" id="gender_1"
                                           value="1"<?= set_value('gender', isset($customer['gender']) ? $customer['gender'] : '') == '1' ? ' checked' : '' ?>>
                                    <label class="form-check-label" for="gender_1">男</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="gender" id="gender_0"
                                           value="0"<?= set_value('gender', isset($customer['gender']) ? $customer['gender'] : '') === '0' ? ' checked' : '' ?>>
                                    <label class="form-check-label" for="gender_0">女</label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="font-weight-bold">生日</label>
                            <div class="form-row">
                                <div class="col">
                                    <select class="form-control" name="birthday_year">
                                        <option value="">生日年</option>
                                        <?php for ($i = date('Y'); $i > date('Y', strtotime('-100 years')); $i--){ ?>
                                            <option value="<?=$i?>"<?php if (set_value('birthday_year', isset($customer['birthday_year']) ? $customer['birthday_year'] : '') == $i){ echo ' selected'; } ?>><?=$i?></option>
                                        <?php } ?>
                                    </select>
                                </div>
                                <div class="col">
                                    <input id="birthday" name="birthday" class="form-control" value="<?= set_value('birthday', isset($customer['birthday']) ? date('m/d', strtotime($customer['birthday'])) : '') ?>"/>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="font-weight-bold">Email</label>
                            <input type="email" name="email" class="form-control"
                                   value="<?= set_value('email', isset($customer['email']) ? $customer['email'] : '') ?>"/>
                        </div>


                        <?php if (!$isOld && isset($customer['id'])) { ?>
                            <div class="form-group">
                                <a target="_blank" href="<?= base_url('/customer/consumer/' . $customer['id']) ?>"
                                   class="btn btn-info btn-sm"><i class="fas fa-search"></i> 歷史消費記錄</a>
                            </div>
                        <?php } ?>
                    </div>

                    <div class="form-group form-check">
                        <input type="checkbox" class="form-check-input" id="isDealer" name="isDealer" value="1"<?php if (set_value('isDealer', (empty($customer['isDealer']) ? 0 : 1) == 1)){ echo 'checked';}?>>
                        <label class="form-check-label" for="isDealer">該顧客為本公司員工</label>
                    </div>

                    <div id="staff_max_alert" class="<?=empty($customer['isDealer']) ? 'd-none' : ''?>">
                        <?php if (isset($customer['id'])){ ?>
                            *本季員工購物額度<?=$staff_max_amount?>元
                        <?php } else { ?>
                            *員工購物首次消費金額不得超過<?=$staff_max_amount?>元
                        <?php } ?>
                        <input type="hidden" id="staff_max_amount" value="<?= $staff_max_amount ?>" />
                    </div>

                    <?php if (!$isOld && !isset($customer['id'])) { ?>
                        <div class="form-group form-check">
                            <input type="checkbox" class="form-check-input" id="hide_customer_info" name="hide_customer_info" value="1"<?php if (set_value('hide_customer_info') == 1){ echo 'checked';}?>>
                            <label class="form-check-label" for="hide_customer_info">顧客無留下完整資料</label>
                        </div>
                    <?php } ?>

                    <div id="reason_wrap" class="d-none">
                        <label class="font-weight-bold">顧客為何無留下完整資料</label>
                        <textarea rows="4" name="reason" class="form-control"><?= set_value('reason') ?></textarea>
                    </div>
                </div>
            </div>

            <div class="my-4">
                <?php if ($customer && $customer['level']){ ?>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="promote_type[]" id="promote_type1" value="1">
                        <label class="form-check-label" for="promote_type1">
                            會員優惠
                        </label>
                    </div>
                <?php } ?>

                <?php if ($promotes){ ?>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="promote_type[]" id="promote_type2" value="2">
                        <label class="form-check-label" for="promote_type2">
                            優惠活動
                            <select id="promote_id" name="promote_id" class="form-control">
                                <option></option>
                                <?php foreach ($promotes as $promote_id => $promote) { ?>
                                    <option value="<?= $promote_id ?>" data-customer_type="<?=$promote['customer_type']?>">
                                        <?= $promote['title'] ?>
                                        <?php
                                        if ($promote['customer_type'] == 3){
                                            echo '(員工活動)';
                                        }
                                        ?>
                                    </option>
                                <?php } ?>
                            </select>
                        </label>
                    </div>
                <?php } ?>

                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="promote_type[]" id="promote_type3" value="3">
                    <label class="form-check-label" for="promote_type3">
                        使用貴賓優惠券
                        <input class="form-control" placeholder="輸入券號" name="coupon_used" />
                    </label>
                </div>
            </div>

            <h3 class="mb-2 mt-4">一般商品</h3>
            <table class="table table-hover table-bordered">
                <tr>
                    <th>項次</th>
                    <th>貨品編號</th>
                    <th>貨品名稱</th>
                    <th>單價</th>
                    <?php if ($dealer['hasStock']){ ?>
                    <th>庫存量</th>
                    <?php } ?>
                    <th>訂購數量</th>
                    <th>金額小計</th>
                    <th>折扣</th>
                    <th>折扣價</th>
                </tr>
                <?php if ($products) {
                    $i = 1;
                    foreach ($products as $product_id => $product) {
                        ?>
                        <tr class="product_item" data-id="<?= $product_id ?>">
                            <td class="text-center"><?= $i ?></td>
                            <td><?= $product['p_num'] ?></td>
                            <td class="item_name"><?= $product['pdName'] ?> <?= $product['intro2'] ?></td>
                            <td class="item_cash text-right">$<?= number_format($product['pdCash']) ?></td>
                            <?php if ($dealer['hasStock']){ ?>
                            <td class="text-right"><?= $product['stock'] ?></td>
                            <?php } ?>
                            <td>
                                <div class="input-group input-group-sm">
                                    <input type="number" min="0" name="items[<?= $product_id ?>][qty]"
                                           class="form-control text-right itemQty"
                                           data-product_id="<?= $product_id ?>"
                                           data-price="<?= intval($product['pdCash']) ?>"
                                        <?php if ($dealer['hasStock']) { ?>
                                            max="<?= $product['stock'] ?>"
                                            data-expired_at="<?= $product['expired_at'] ?>"
                                            <?php if (!$product['stock']){ ?>
                                                disabled
                                                placeholder="無庫存"
                                            <?php } ?>
                                        <?php } ?>
                                            data-pao_month="<?= !empty($product['pao']) ? $product['pao']['pao_month'] : '' ?>"
                                            value="<?= set_value('items[' . $product_id . '][qty]', '') ?>"/>
                                </div>
                            </td>
                            <td class="item_subtotal text-right"></td>
                            <td class="item_discount text-right" data-discount=""></td>
                            <td class="item_total text-right"></td>
                        </tr>
                        <?php
                        $i++;
                    }
                }
                ?>
            </table>

            <?php if ($combos) { ?>
            <h3 class="mb-2 mt-4">組合商品</h3>
            <table class="table table-hover table-bordered">
                <tr>
                    <th>名稱</th>
                    <th>明細</th>
                    <th>總金額</th>
                    <?php if ($dealer['hasStock']){ ?>
                    <th>庫存量</th>
                    <?php } ?>
                    <th>訂購數量</th>
                    <th>金額小計</th>
                    <th>折扣</th>
                    <th>折扣價</th>
                </tr>
                <?php
                    $i = 1;
                    foreach ($combos as $combo_id => $combo) {
                        ?>
                        <tr class="combo_item" data-id="<?= $combo_id ?>">
                            <td><?= $combo['name'] ?></td>
                            <td>
                                <ol>
                                    <?php
                                    foreach ($combo['items'] as $item){
                                        ?>
                                        <li class="combo_item_name" data-id="<?=$item['product']['pdId']?>" data-name="<?=$item['product']['pdName'] . $item['product']['intro2'] ?>" data-qty="<?=$item['qty'] ?>" data-price="<?= intval($item['price']) ?>" data-pao_month="<?= !empty($item['product']['pao']) ? $item['product']['pao']['pao_month'] : '' ?>">
                                            <?=$item['product']['pdName'] . $item['product']['intro2'] . ' X' . $item['qty'] ?>
                                        </li>
                                        <?php
                                    }
                                    ?>
                                </ol>
                            </td>
                            <td class="text-right"><?= '$' . number_format($combo['total']) ?></td>
                            <?php if ($dealer['hasStock']){ ?>
                                <td class="text-right"><?= $combo['stock'] ?></td>
                            <?php } ?>
                            <td>
                                <div class="input-group input-group-sm">
                                    <input type="number" min="0" name="combo_items[<?= $combo_id ?>][qty]"
                                           class="form-control text-right combo_itemQty"
                                           data-price="<?= intval($combo['total']) ?>"
                                           data-combo_id="<?= $combo_id ?>"
                                        <?php if ($dealer['hasStock']) { ?>
                                            max="<?= $combo['stock'] ?>"
                                            <?php if (!$combo['stock']){ ?>
                                                disabled
                                                placeholder="無庫存"
                                            <?php } ?>
                                        <?php } ?>
                                           value="<?= set_value('combo_items[' . $combo_id . '][qty]', '') ?>"/>
                                </div>
                            </td>
                            <td class="combo_item_subtotal text-right"></td>
                            <td class="combo_item_discount text-right" data-discount=""></td>
                            <td class="combo_item_total text-right"></td>
                        </tr>
                        <?php
                        $i++;
                    }
                ?>
            </table>
            <?php } ?>

            <section id="gift-section" class="d-none">
                <h3 class="mb-2 mt-4">贈品</h3>
                <table class="table table-hover table-bordered">
                    <thead>
                        <tr>
                            <th>貨品名稱</th>
                            <th>贈品選擇</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </section>

            <?php if ($free_packages) { ?>
            <h3 class="mb-2 mt-4">免費包裝商品</h3>
            <table class="table table-hover table-bordered">
                <tr>
                    <th>貨品編號</th>
                    <th>貨品名稱</th>
                    <?php if ($dealer['hasStock']){ ?>
                        <th>庫存量</th>
                    <?php } ?>
                    <th>訂購數量</th>
                </tr>
                <?php
                    $i = 1;
                    foreach ($free_packages as $product_id => $free_package) {
                        ?>
                        <tr>
                            <td><?= $free_package['product']['p_num'] ?></td>
                            <td class="package_name"><?= $free_package['product']['pdName'] . $free_package['product']['intro2']?></td>
                            <?php if ($dealer['hasStock']){ ?>
                                <td class="text-right"><?= $free_package['stock'] ?></td>
                            <?php } ?>
                            <td>
                                <div class="input-group input-group-sm">
                                    <input type="number" min="0" name="package_items[<?= $product_id ?>][qty]"
                                           class="form-control text-right package_itemQty"
                                           data-product_id="<?= $product_id ?>"
                                        <?php if ($dealer['hasStock']) { ?>
                                            max="<?= $free_package['stock'] ?>"
                                            <?php if (!$free_package['stock']){ ?>
                                                disabled
                                                placeholder="無庫存"
                                            <?php } ?>
                                        <?php } ?>
                                           data-pao_month="<?= !empty($free_package['product']['pao']) ? $free_package['product']['pao']['pao_month'] : '' ?>"
                                           value="<?= set_value('package_items[' . $product_id . '][qty]', '') ?>"/>
                                </div>
                            </td>
                        </tr>
                        <?php
                        $i++;
                    }
                ?>
            </table>
            <?php } ?>

            <table class="table table-hover table-bordered mt-4">
                <tr>
                    <td class="text-right font-weight-bold">小計</td>
                    <td id="subtotal_text" class="text-right font-weight-bold"></td>
                </tr>
                <tr id="totalDiscount" class="d-none">
                    <td class="text-right font-weight-bold">優惠折扣金額</td>
                    <td id="totalDiscount_text" class="text-right font-weight-bold"></td>
                </tr>
                <tr id="totalReachDiscount" class="d-none">
                    <td class="text-right font-weight-bold">滿額折扣</td>
                    <td id="totalReachDiscount_text" class="text-right font-weight-bold"></td>
                </tr>
                <tr>
                    <td class="text-right font-weight-bold">總計</td>
                    <td id="total_text" data-total="" class="text-right font-weight-bold"></td>
                </tr>
                <tr>
                    <td class="text-right font-weight-bold">備註</td>
                    <td>
                        <textarea rows="4" name="memo" class="form-control"><?= set_value('memo') ?></textarea>
                    </td>
                </tr>
            </table>

            <table class="table table-hover table-bordered mt-4">
                <tr id="coupon_info" class="d-none">
                    <td colspan="3">
                        <p>「皮瑪斯九折優惠券」說明：</p>
                        <p>一.取得辦法：</p>
                        <ol>
                            <li>單筆消費「一顆橄欖」商品「2000元以上(含2000元)、未滿6000元」，則發放「皮瑪斯九折優惠券」乙張。</li>
                            <li>單筆消費「一顆橄欖」商品「6000元以上(含6000元)」，則發放「皮瑪斯九折優惠券」貳張。</li>
                        </ol>
                        <p>二.使用辦法：</p>
                        <ol>
                            <li>本券需於「皮瑪斯工坊門市」委託護理時提出；一張優惠券僅適用一物件，並依當時價格表之「九折」優惠計費。</li>
                            <li>本券可移轉他人使用，係「認券不認人」；使用優惠券，應於委託護理時付清費用。</li>
                            <li>需依皮瑪斯書面公告，本券方可併用其他優惠。</li>
                            <li>本券需經皮瑪斯驗證，方屬有效。</li>
                        </ol>
                    </td>
                </tr>
                <tr id="coupon_1" class="d-none">
                    <td class="text-right font-weight-bold">滿$2000核發折價券</td>
                    <td class="text-right font-weight-bold">折價券號</td>
                    <td>
                        <input disabled name="coupon_number_1" class="form-control" value="" />
                    </td>
                </tr>
                <tr id="coupon_2" class="d-none">
                    <td class="text-right font-weight-bold">滿$6000核發折價券</td>
                    <td class="text-right font-weight-bold">折價券號</td>
                    <td>
                        <input disabled name="coupon_number_2" class="form-control" value="" />
                    </td>
                </tr>
            </table>

            <div class="mt-4 mb-2">
                <div class="form-group">
                    <label class="font-weight-bold">付款方式</label>
                    <?php
                    echo form_dropdown('payment_type', $payment_type, set_value('payment_type'), 'id="payment_type" class="form-control"');
                    ?>
                </div>

                <div id="recipient_info" class="d-none">
                    <div class="form-group">
                        <label class="font-weight-bold">收件人姓名</label>
                        <input name="recipient_name" class="form-control"
                               value="<?= set_value('recipient_name') ?>"/>
                    </div>
                    <div class="form-group">
                        <label class="font-weight-bold">收件人電話</label>
                        <input name="recipient_phone" class="form-control"
                               value="<?= set_value('recipient_phone') ?>"/>
                    </div>
                    <div class="form-group">
                        <label class="font-weight-bold">收件人地址</label>
                        <input name="recipient_address" class="form-control"
                               value="<?= set_value('recipient_address') ?>"/>
                    </div>
                </div>

                <div id="shipout_info" class="d-none">
                    <div class="form-group">
                        <label class="font-weight-bold">其他門市取貨</label>
                        <select id="shipout_retailer_id" name="shipout_retailer_id" class="form-control">
                            <option value=""></option>
                            <?php foreach ($shipout_retailers as $retailer_id => $retailer) { ?>
                                <option value="<?= $retailer_id ?>"><?= $retailer['company'] ?></option>
                            <?php } ?>
                        </select>
                    </div>
                </div>
            </div>

            <input type="hidden" id="member_discount" value="<?= $member_discount ?>">

            <div id="expired_submit_wrap" class="form-group text-center">
                <button type="button" id="btn-checkout" class="btn btn-success">
                    填寫商品有效期限
                </button>
            </div>

            <div id="direct_submit_wrap" class="form-group text-center d-none">
                <input type="submit" name="submit_recommend" class="btn btn-success mr-auto" value="送出消費紀錄/進行推薦作業"/>
                <input type="submit" name="submit_wo_recommend" class="btn btn-success" value="送出消費紀錄/不進行推薦作業"/>
            </div>

            <div class="modal fade" id="productExpirationModal" tabindex="-1" role="dialog">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">填寫商品有效期限</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <table class="table table-bordered">
                                <thead>
                                <tr>
                                    <th>貨品名稱</th>
                                    <td>數量</td>
                                    <td>有效期限</td>
                                </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                        <div class="modal-footer">
                            <input type="submit" name="submit_recommend" class="btn btn-success mr-auto" value="送出消費紀錄/進行推薦作業"/>
                            <input type="submit" name="submit_wo_recommend" class="btn btn-success" value="送出消費紀錄/不進行推薦作業"/>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>



<link rel="stylesheet" href="<?= base_url('/css/datepicker.min.css')?>" />
<script src="<?= base_url('/js/datepicker.min.js')?>"></script>

<script>
    var promotes = <?=json_encode($promotes)?>;
    $().ready(function () {
        $('#payment_type').change(function(){
            var payment_type = parseInt($(this).val());
            switch (payment_type){
                case 4: //貨到付款
                    $('#recipient_info').removeClass('d-none');
                    $('#shipout_info').addClass('d-none');
                    $('#expired_submit_wrap').addClass('d-none');
                    $('#direct_submit_wrap').removeClass('d-none');
                    break;
                case 5: //其他門市取貨
                    $('#recipient_info').addClass('d-none');
                    $('#shipout_info').removeClass('d-none');
                    $('#expired_submit_wrap').addClass('d-none');
                    $('#direct_submit_wrap').removeClass('d-none');
                    break;
                default:
                    $('#recipient_info').addClass('d-none');
                    $('#shipout_info').addClass('d-none');
                    $('#expired_submit_wrap').removeClass('d-none');
                    $('#direct_submit_wrap').addClass('d-none');
                    break;
            }
        });
        $('#payment_type').trigger('change');

        $('#hide_customer_info').change(function(){
            if ($(this).prop('checked')){
                $('#customer_info').addClass('d-none');
                $('#customer_info input').prop('disabled', true);
                $('#customer_info select').prop('disabled', true);
                $('#reason_wrap').removeClass('d-none');
            } else {
                $('#customer_info').removeClass('d-none');
                $('#customer_info input').prop('disabled', false);
                $('#customer_info select').prop('disabled', false);
                $('#reason_wrap').addClass('d-none');
            }
        });
        $('#hide_customer_info').trigger('change');

        $('#isDealer').change(function(){
            if ($(this).prop('checked')){
                $('#staff_max_alert').removeClass('d-none');
                $.each($('#promote_id option'), function(){
                    $(this).prop('disabled', false);
                });
            } else {
                $('#staff_max_alert').addClass('d-none');
                $.each($('#promote_id option'), function(){
                    if ($(this).data('customer_type') == '3'){
                        if ($('#promote_type2').prop('checked')){
                            if ($(this).prop("selected")){
                                $('#promote_type2').prop('checked', false);
                                $(this).prop("selected", false);
                                calc_total();
                            }
                        } else {
                            $(this).prop("selected", false);
                        }
                        $(this).prop('disabled', true);
                    }
                });
            }
        });
        $('#isDealer').trigger('change');

        $("#birthday").datepicker({
            format: 'mm/dd'
        });

        $('#btn-firstTime').click(function(){
            $(this).parent().remove();
            $('#order_wrap').removeClass('d-none');
        });

        calc_total();

        $('a.show_picture').tooltip({
            animated: 'fade',
            placement: 'top',
            html: true
        });

        $('#promote_type1').change(function () {
            var selected_promote_id = $('#promote_id').val();
            if (!selected_promote_id){
                $('#promote_type3').prop('checked', false);
            } else if (promotes[selected_promote_id]){
                var go_with_member = parseInt(promotes[selected_promote_id]['go_with_member']) || 0;
                if ($('#promote_type2').prop('checked') && !go_with_member){
                    $('#promote_type2').prop('checked', false);
                }
                $('#promote_type3').prop('checked', false);
                calc_total();
            } else {
                alert('請選擇優惠活動');
            }
        });

        $('#promote_type2').change(function () {
            var selected_promote_id = $('#promote_id').val();
            if (promotes[selected_promote_id]){
                var go_with_member = parseInt(promotes[selected_promote_id]['go_with_member']) || 0;
                if ($('#promote_type1').prop('checked') && !go_with_member){
                    $('#promote_type1').prop('checked', false);
                }
                var go_with_coupon = parseInt(promotes[selected_promote_id]['go_with_coupon']) || 0;
                if ($('#promote_type3').prop('checked') && !go_with_coupon){
                    $('#promote_type3').prop('checked', false);
                }
                calc_total();
            } else {
                alert('請選擇優惠活動');
            }
        });

        $('#promote_type3').change(function () {
            var selected_promote_id = $('#promote_id').val();
            if (!selected_promote_id) {
                $('#promote_type1').prop('checked', false);
            } else if (promotes[selected_promote_id]){
                var go_with_coupon = parseInt(promotes[selected_promote_id]['go_with_coupon']) || 0;
                if ($('#promote_type2').prop('checked') && !go_with_coupon){
                    $('#promote_type2').prop('checked', false);
                }
                $('#promote_type1').prop('checked', false);
                calc_total();
            } else {
                alert('請選擇優惠活動');
            }
        });

        $('#orderForm input.itemQty, #orderForm input.combo_itemQty, #promote_id').change(function () {
            calc_total();
        });

        function calc_total() {
            var subtotal = 0;
            var total = 0;
            var totalDiscount = 0;
            var totalReachDiscount = 0;

            var discount_type = 'P';
            var discount = 100;
            var promote = [];

            if ($('#promote_type1').prop('checked')){
                discount = parseInt($('#member_discount').val()) || 100;
            }

            for (var pk in promotes) {
                for (var mk in promotes[pk]['methods']) {
                    promotes[pk]['methods'][mk]['totalDiscount'] = 0;
                    promotes[pk]['methods'][mk]['totalGift'] = 0;
                }
            }

            $('#gift-section table tbody').html('');
            $('#gift-section').addClass('d-none');
            $('#subtotal_text').text('');
            $('#total_text').text('');
            $('#totalDiscount_text').text('');
            $('#totalDiscount').addClass('d-none');
            $('#totalReachDiscount_text').text('');
            $('#totalReachDiscount').addClass('d-none');

            $('#orderForm input.itemQty').each(function () {
                var item = $(this).parents('tr');
                var qty = parseInt($(this).val()) || 0;
                var price = parseInt($(this).data('price'));
                var product_id = parseInt($(this).data('product_id'));

                var item_discount = discount;
                var item_discount_type = discount_type;
                if (qty > 0) {
                    var item_subtotal = qty * price;

                    if (item_discount_type == 'P') {
                        var item_total = Math.round(item_subtotal * item_discount / 100);
                    } else {
                        var item_total = item_subtotal - item_discount;
                        item_discount = Math.round(item_total / item_subtotal * 100);
                    }

                    if ($('#promote_type2').prop('checked')) {
                        var selected_promote_id = $('#promote_id').val();
                        promote = promotes[selected_promote_id];
                        if (promote) {
                            for (var key in promote['methods']) {
                                var method = promote['methods'][key];
                                switch (method['promote_type_id']) {
                                    case '1': //產品折扣
                                        var item_match = false;
                                        if (method['items'] && method['items'].length) {
                                            for (var ki in method['items']) {
                                                var pitem = method['items'][ki];
                                                if (pitem['id'] == product_id) {
                                                    item_match = true;
                                                    break;
                                                }
                                            }
                                        } else {
                                            item_match = true;
                                        }

                                        if (item_match) {
                                            if (method['discount_type'] == 'P') {
                                                item_total = Math.round(item_total * method['discount'] / 100);
                                                item_discount = Math.round(item_total / item_subtotal * 100);
                                            } else {
                                                item_total -= method['discount'];
                                                item_discount = Math.round(item_total / item_subtotal * 100);
                                            }
                                        }
                                        break;
                                    case '2': //滿額折扣
                                        var item_match = false;
                                        if (method['items'] && method['items'].length) {
                                            for (var ki in method['items']) {
                                                var pitem = method['items'][ki];
                                                if (pitem['id'] == product_id) {
                                                    item_match = true;
                                                    break;
                                                }
                                            }
                                        } else {
                                            item_match = true;
                                        }

                                        if (item_match) {
                                            promote['methods'][key]['totalDiscount'] += item_total;
                                        }
                                        break;
                                    case '3': //贈品
                                        var item_match = false;
                                        if (method['relatives'] && method['relatives'].length) {
                                            for (var ki in method['relatives']) {
                                                var pitem = method['relatives'][ki];
                                                if (pitem['type'] == 'product' && pitem['id'] == product_id) {
                                                    item_match = true;
                                                    break;
                                                }
                                            }
                                        } else {
                                            item_match = true;
                                        }

                                        if (item_match) {
                                            if (!('totalGift' in promote['methods'][key])) {
                                                promote['methods'][key]['totalGift'] = 0;
                                            }
                                            promote['methods'][key]['totalGift'] += item_total;
                                        }
                                        break;
                                }
                            }
                        }
                    }

                    subtotal += item_subtotal;
                    totalDiscount += item_subtotal - item_total;
                    total += item_total;
                } else {
                    item_subtotal = 0;
                    item_total = 0;
                }

                item.find('.item_discount').text(item_discount + '%').data('discount', item_discount);
                item.find('.item_subtotal').text('$' + numberWithCommas(item_subtotal));
                item.find('.item_total').text('$' + numberWithCommas(item_total));
            });

            $('#orderForm input.combo_itemQty').each(function () {
                var item = $(this).parents('tr');
                var qty = parseInt($(this).val()) || 0;
                var price = parseInt($(this).data('price'));
                var combo_id = parseInt($(this).data('combo_id'));

                var combo_item_discount = discount;
                var combo_item_discount_type = discount_type;

                if (qty > 0) {
                    var combo_item_subtotal = qty * price;

                    if (combo_item_discount_type == 'P') {
                        var combo_item_total = Math.round(combo_item_subtotal * combo_item_discount / 100);
                    } else {
                        var combo_item_total = combo_item_subtotal - combo_item_discount;
                        combo_item_discount = Math.round(combo_item_total / combo_item_subtotal * 100);
                    }

                    if ($('#promote_type2').prop('checked')) {
                        var selected_promote_id = $('#promote_id').val();
                        promote = promotes[selected_promote_id];
                        if (promote) {
                            for (var key in promote['methods']) {
                                var method = promote['methods'][key];
                                switch (method['promote_type_id']) {
                                    case '1': //產品折扣
                                        var item_match = false;
                                        if (method['items'] && method['items'].length) {
                                            for (var ki in method['items']) {
                                                var pitem = method['items'][ki];
                                                if (pitem['type'] == 'combo' && pitem['id'] == combo_id) {
                                                    item_match = true;
                                                    break;
                                                }
                                            }
                                        } else {
                                            item_match = true;
                                        }

                                        if (item_match) {
                                            if (method['discount_type'] == 'P') {
                                                combo_item_total = Math.round(combo_item_total * method['discount'] / 100);
                                                combo_item_discount = Math.round(combo_item_total / combo_item_subtotal * 100);
                                            } else {
                                                combo_item_total -= method['discount'];
                                                combo_item_discount = Math.round(combo_item_total / combo_item_subtotal * 100);
                                            }
                                        }
                                        break;
                                    case '2': //滿額折扣
                                        var item_match = false;
                                        if (method['items'] && method['items'].length) {
                                            for (var ki in method['items']) {
                                                var pitem = method['items'][ki];
                                                if (pitem['type'] == 'combo' && pitem['id'] == combo_id) {
                                                    item_match = true;
                                                    break;
                                                }
                                            }
                                        } else {
                                            item_match = true;
                                        }

                                        if (item_match) {
                                            promote['methods'][key]['totalDiscount'] += combo_item_total;
                                        }
                                        break;
                                    case '3': //贈品
                                        var item_match = false;
                                        if (method['relatives'] && method['relatives'].length) {
                                            for (var ki in method['relatives']) {
                                                var pitem = method['relatives'][ki];
                                                if (pitem['type'] == 'combo' && pitem['id'] == combo_id) {
                                                    item_match = true;
                                                    break;
                                                }
                                            }
                                        } else {
                                            item_match = true;
                                        }

                                        if (item_match) {
                                            promote['methods'][key]['totalGift'] += combo_item_total;
                                        }
                                        break;
                                }
                            }
                        }
                    }

                    subtotal += combo_item_subtotal;
                    totalDiscount += combo_item_subtotal - combo_item_total;
                    total += combo_item_total;
                } else {
                    combo_item_subtotal = 0;
                    combo_item_total = 0;
                }

                item.find('.combo_item_discount').text(combo_item_discount + '%').data('discount', combo_item_discount);
                item.find('.combo_item_subtotal').text('$' + numberWithCommas(combo_item_subtotal));
                item.find('.combo_item_total').text('$' + numberWithCommas(combo_item_total));
            });

            if (promote){
                var gift_html = '';
                for (var key in promote['methods']) {
                    var method = promote['methods'][key];
                    switch (method['promote_type_id']){
                        case '2': //滿額折扣
                            if ('totalDiscount' in method && method['totalDiscount'] >= method['limit']) {
                                totalReachDiscount += parseInt(method['discount']);
                            }
                            break;
                        case '3': //贈品
                            if ('totalGift' in method && method['totalGift'] >= method['limit']) {
                                for (var ki in method['items']) {
                                    var pitem = method['items'][ki];
                                    gift_html += '<tr>';
                                    gift_html += '<td>' + pitem['name'] + '</td>';
                                    gift_html += '<td class="gift_qty text-right">';
                                    if (method['options'] && method['options']['single']){
                                        gift_html += '<input type="radio" id="gifts-' + method['id'] + '-' + pitem['type'] + '-' + pitem['id'] + '" class="gift_itemQty" name="gifts[' + method['id'] + ']" value="' + pitem['type'] + '-' + pitem['id'] + '" checked data-method="' + method['id'] + '" data-type="' + pitem['type'] + '" data-id="' + pitem['id'] + '" data-pao_month="' + pitem['pao_month'] + '" />';
                                    } else {
                                        gift_html += '1<input type="hidden" class="gift_itemQty" data-method="' + method['id'] + '" data-type="' + pitem['type'] + '" data-id="' + pitem['id'] + '" data-pao_month="' + pitem['pao_month'] + '" value="1" />';
                                    }
                                    gift_html += '</td>';
                                    gift_html += '</tr>';
                                }
                            }
                            break;
                    }
                }
                total -= totalReachDiscount;

                if (gift_html) {
                    $('#gift-section table tbody').html(gift_html);
                    $('#gift-section').removeClass('d-none');
                }
            }

            $('#subtotal_text').text('$' + numberWithCommas(subtotal));
            if (totalDiscount > 0){
                $('#totalDiscount_text').text('- $' + numberWithCommas(totalDiscount));
                $('#totalDiscount').removeClass('d-none');
            }
            if (totalReachDiscount > 0){
                $('#totalReachDiscount_text').text('- $' + numberWithCommas(totalReachDiscount));
                $('#totalReachDiscount').removeClass('d-none');
            }
            $('#total_text').text('$' + numberWithCommas(total)).data('total', total);

            checkCouponApprove(total);
        }
    });

    function checkCouponApprove(total){
        $('#coupon_info').addClass('d-none');
        $('#coupon_1').addClass('d-none').find('input').prop('disabled', true).val('');
        $('#coupon_2').addClass('d-none').find('input').prop('disabled', true).val('');

        if (total >= 2000){
            $('#coupon_info').removeClass('d-none');
            $('#coupon_1').removeClass('d-none').find('input').prop('disabled', false);

            if (total >= 6000){
                $('#coupon_2').removeClass('d-none').find('input').prop('disabled', false);
            }
        }
    }

    function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    $("#orderForm").keydown(function(e){
        if(e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    });

    $('#btn-checkout').click(function(){
        var hasQty = false;
        $.each($('input.itemQty'), function () {
            if ($(this).val() > 0) {
                hasQty = true;
                return false;
            }
        });

        if (!hasQty) {
            $.each($('input.combo_itemQty'), function () {
                if ($(this).val() > 0) {
                    hasQty = true;
                    return false;
                }
            });
        }

        if (!hasQty) {
            alert('您尚未選購商品');
        } else {
            var expiration_html = '';
            $('#orderForm input.itemQty').each(function () {
                var qty = parseInt($(this).val()) || 0;
                if (qty > 0) {
                    var item = $(this).parents('tr');
                    var product_name = item.find('td.item_name').text();
                    var item_discount = item.find('td.item_discount').data('discount');
                    var product_id = parseInt($(this).data('product_id'));
                    var pao_month = parseInt($(this).data('pao_month'));
                    var price = parseInt($(this).data('price'));
                    var expired_at = $(this).data('expired_at');
                    var item_total = Math.round(price * item_discount / 100);
                    for (var i = 0; i < qty; i++) {
                        expiration_html += '<tr>' +
                            '<td>' + product_name + '</td>' +
                            '<td>1</td>' +
                            '<td><input type="date" class="expired_dates" name="expired_dates[' + product_id + '][]" data-pao_month="' + pao_month + '" data-price="' + item_total + '" value="' + expired_at + '" /></td>' +
                            '</tr>';
                    }
                }
            });

            $('#orderForm input.combo_itemQty').each(function () {
                var item = $(this).parents('tr');
                var combo_qty = parseInt($(this).val()) || 0;
                var combo_id = parseInt($(this).data('combo_id')) || 0;
                if (combo_qty > 0 && combo_id > 0) {
                    item.find('li.combo_item_name').each(function () {
                        var product_name = $(this).data('name');
                        var product_id = parseInt($(this).data('id'));
                        var product_qty = parseInt($(this).data('qty')) || 0;
                        var pao_month = parseInt($(this).data('pao_month'));
                        var item_total = parseInt($(this).data('price'));
                        if (product_qty > 0) {
                            for (var i = 0; i < combo_qty * product_qty; i++) {
                                expiration_html += '<tr>' +
                                    '<td>[組合]' + product_name + '</td>' +
                                    '<td>1</td>' +
                                    '<td><input type="date" class="expired_dates" name="expired_dates[' + product_id + '][]" data-pao_month="' + pao_month + '" data-price="' + item_total + '" /></td>' +
                                    '</tr>';
                            }
                        }
                    });
                }
            });

            $('#orderForm input.package_itemQty').each(function () {
                var qty = parseInt($(this).val()) || 0;
                if (qty > 0) {
                    var item = $(this).parents('tr');
                    var pao_month = parseInt($(this).data('pao_month'));
                    var package_name = item.find('td.package_name').text();
                    var product_id = parseInt($(this).data('product_id'));
                    for (var i = 0; i < qty; i++) {
                        expiration_html += '<tr>' +
                            '<td>[包裝]' + package_name + '</td>' +
                            '<td>1</td>' +
                            '<td><input type="date" class="expired_dates" name="expired_dates[' + product_id + '][]" data-pao_month="' + pao_month + '" data-price="0" /></td>' +
                            '</tr>';
                    }
                }
            });

            $('#orderForm input.gift_itemQty').each(function () {
                if ($(this).prop('type') == 'hidden' || ($(this).prop('type') == 'radio' && $(this).prop('checked') == true)) {
                    var gift_method = parseInt($(this).data('method')) || 0;
                    var gift_type = $(this).data('type');
                    var gift_id = parseInt($(this).data('id')) || 0;
                    if (gift_method > 0 && gift_id > 0) {
                        if (gift_type == 'product') {
                            $.each($('tr.product_item'), function () {
                                var product_id = parseInt($(this).data('id')) || 0;
                                if (product_id > 0 && gift_id == product_id) {
                                    var pao_month = parseInt($(this).data('pao_month'));
                                    var product_name = $(this).find('td.item_name').text();
                                    expiration_html += '<tr>' +
                                        '<td>[贈品]' + product_name + '</td>' +
                                        '<td>1</td>' +
                                        '<td><input type="date" class="expired_dates" name="expired_dates[' + product_id + '][]" data-pao_month="' + pao_month + '" data-price="0" /></td>' +
                                        '</tr>';
                                    return false;
                                }
                            });
                        } else if (gift_type == 'combo') {
                            $.each($('tr.combo_item'), function () {
                                var combo_id = parseInt($(this).data('id')) || 0;
                                if (combo_id > 0 && gift_id == combo_id) {
                                    $(this).find('li.combo_item_name').each(function () {
                                        var product_name = $(this).data('name');
                                        var product_id = parseInt($(this).data('id'));
                                        var product_qty = parseInt($(this).data('qty')) || 0;
                                        var pao_month = parseInt($(this).data('pao_month'));
                                        if (product_qty > 0) {
                                            for (var i = 0; i < product_qty; i++) {
                                                expiration_html += '<tr>' +
                                                    '<td>[贈品]' + product_name + '</td>' +
                                                    '<td>1</td>' +
                                                    '<td><input type="date" class="expired_dates" name="expired_dates[' + product_id + '][]" data-pao_month="' + pao_month + '" data-price="0" /></td>' +
                                                    '</tr>';
                                            }
                                        }
                                    });
                                    return false;
                                }
                            });
                        }
                    }
                }
            });

            $('#productExpirationModal table tbody').html(expiration_html);

            $('#productExpirationModal').modal('show');
        }
    });

    $("#orderForm").find('input[type="submit"]').click(function (e) {
        if ($('#isDealer').prop('checked')) {
            var total = $('#total_text').data('total');
            var staff_max_amount = $('#staff_max_amount').val();
            $('#orderForm input.expired_dates').each(function () {
                var expired_date = $(this).val();
                var pao_month = parseInt($(this).data('pao_month')) || 0;
                var price = parseInt($(this).data('price')) || 0;

                if (expired_date && pao_month > 0 && price > 0){
                    var nd = new Date();
                    var xd = new Date(expired_date);
                    xd.setMonth(xd.getMonth() - pao_month);
                    if (nd.getTime() >= xd.getTime()){
                        total -= price;
                    }
                }
            });

            if (total > staff_max_amount){
                alert('超過員工購物消費金額');
                return false;
            }
        }

        if (confirm('請確認是否送出消費紀錄?')) {
            $.each($('input.itemQty'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });

            $.each($('input.combo_itemQty'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });

            $.each($('input.package_itemQty'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });
        } else {
            return false;
        }
    });
</script><file_sep>/application/migrations/061_update_shipment_revise_id.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_shipment_revise_id extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_column('olive_shipments', [
            'shipment_id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'after' => 'id',
            ],
            'isRevised' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'isConfirmed',
            ],
            'isReturn' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'isRevised',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_shipments', 'shipment_id');
        $this->dbforge->drop_column('olive_shipments', 'isRevised');
        $this->dbforge->drop_column('olive_shipments', 'isReturn');
    }
}<file_sep>/application/migrations/050_update_retailer_sales_dealer.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_retailer_sales_dealer extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_retailers', [
            'sales_dealer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
                'after' => 'sales_retailer_id',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_retailers', 'sales_dealer_id');
    }
}<file_sep>/application/models/Customer_level_model.php
<?php

class Customer_level_model extends MY_Model
{
    public $table = 'olive_customer_levels';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['customers'] = array('Customer_model', 'customer_level_id', 'id');
    }

    public function getLevelSelect()
    {
        $_levels = $this
            ->order_by('id', 'asc')
            ->get_all();
        $levels = [];
        foreach ($_levels as $level){
            $levels[$level['id']] = $level['title'];
        }
        return $levels;
    }

    public function getLevelFirstDiscount()
    {
        $level = $this
            ->order_by('id', 'asc')
            ->get();
        return $level['discount'];
    }
}

?>
<file_sep>/application/models/Purchase_model.php
<?php

class Purchase_model extends MY_Model
{
    public $table = 'olive_purchases';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['items'] = array('Purchase_item_model', 'purchase_id', 'id');
        $this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
        $this->has_one['shipin_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipin_retailer_id');
        $this->has_one['shipout_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipout_retailer_id');
        $this->has_one['confirm'] = array('foreign_model' => 'Confirm_model', 'foreign_table' => 'olive_confirms', 'foreign_key' => 'confirm_id', 'local_key' => 'id');
        $this->has_many['payments'] = array('Payment_model', 'pay_id', 'id');
        $this->has_many['shipments'] = array('Shipment_model', 'ship_id', 'id');
        $this->has_one['transfer_to'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'transfer_id');
        $this->has_one['transfer_from'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'transfer_id', 'local_key' => 'id');
        $this->has_one['order_transfer'] = array('foreign_model' => 'Order_transfer_model', 'foreign_table' => 'olive_order_transfers', 'foreign_key' => 'purchase_id', 'local_key' => 'id');
    }

    public function getNextPurchaseSerialNum()
    {
        $purchase = $this
            ->with_trashed()
            ->where('DATE_FORMAT(created_at,"%Y-%m") = "' . date('Y-m') . '"', null, null, false, false, true)
            ->order_by('serialNum', 'desc')
            ->get();

        if ($purchase) {
            $num = (int)$purchase['serialNum'] + 1;
            return str_pad($num, 5, '0', STR_PAD_LEFT);
        } else {
            return '00001';
        }
    }

    public function checkHasAllowance($purchase_id)
    {
        $this->load->model('payment_model');

        //銷貨折讓
        $hasAllowance = false;
        $payments = $this->payment_model
            ->where('pay_type', 'shipment_allowance')
            ->where('pay_id', $purchase_id)
            ->get_all();

        if ($payments) {
            foreach ($payments as $payment){
                if (!$payment['active'] || !$payment['isConfirmed']){
                    $hasAllowance = true;
                    break;
                }
            }
        }

        if (!$hasAllowance){
            $this->update([
                'isAllowance' => 0,
            ], ['id' => $purchase_id]);
        }
    }

    public function checkCorrect($purchase_id)
    {
        $purchase = $this
            ->get($purchase_id);

        if ($purchase['isShipped'] && !$purchase['isRevised']){
            $this->update(['isShipConfirmed' => 1], ['id' => $purchase_id]);

            $this->load->model('commission_model');
            $this->commission_model->record($purchase_id);
        }
    }

    public function transfer_purchase($purchase_id, $new_shipout_retailer_id, $dealer)
    {
        $purchase = $this->purchase_model
            ->with_transfer_from()
            ->with_shipout_retailer('fields:company,invoice_title,address')
            ->with_items()
            ->get($purchase_id);

        if ($purchase['retailer_id'] == $new_shipout_retailer_id || $purchase['shipin_retailer_id'] == $new_shipout_retailer_id){
            return false;
        }

        $new_retailer_id = $purchase['shipout_retailer_id'];
        $new_retailer = $purchase['shipout_retailer'];

        if (empty($purchase['transfer_from'])){
            $new_shipin_retailer_id = $purchase['shipin_retailer_id'];
            $new_shipin_address = $purchase['shipin_address'];
        } else {
            $new_shipin_retailer_id = $purchase['transfer_from']['shipout_retailer_id'];
            $new_shipin_address = $purchase['transfer_from']['shipout_retailer']['address'];
        }


        $purchaseSerialNum = $this->getNextPurchaseSerialNum();

        $insert_data = [
            'retailer_id' => $new_retailer_id,
            'retailer_address' => $new_retailer['address'],
            'shipout_retailer_id' => $new_shipout_retailer_id,
            'shipin_retailer_id' => $new_shipin_retailer_id,
            'shipin_address' => $new_shipin_address,
            'serialNum' => $purchaseSerialNum,
            'purchaseNum' => date('Ym') . $purchaseSerialNum,
            'memo' => $purchase['memo'],
            'isInvoice' => $purchase['isInvoice'],
            'dealer_id' => $dealer['id'],
        ];

        if ($purchase['isInvoice']) {
            $insert_data['invoice_retailer'] = $new_retailer['invoice_title'];
            $insert_data['invoice_send_retailer'] = $new_retailer['invoice_title'];
            $insert_data['invoice_send_address'] = $new_retailer['address'];
        }

        $new_purchase_id = $this->insert($insert_data);

        //計算折扣
        $this->load->model('retailer_relationship_model');
        $relative_shipout_retailer = $this->retailer_relationship_model
            ->where('relation_type', 'shipout')
            ->where('retailer_id', $new_retailer_id)
            ->where('relation_retailer_id', $new_shipout_retailer_id)
            ->get();

        $discount = 100;
        if ($relative_shipout_retailer){
            if ($relative_shipout_retailer['discount']){
                $discount = $relative_shipout_retailer['discount'];
            }
        }

        if ($purchase['isInvoice']) {
            $relative_invoice_retailer = $this->retailer_relationship_model
                ->where('relation_type', 'invoice')
                ->where('retailer_id', $new_retailer_id)
                ->where('relation_retailer_id', $new_shipout_retailer_id)
                ->where('alter_retailer_id', $new_retailer_id)
                ->get();
            if ($relative_invoice_retailer){
                if ($relative_invoice_retailer['discount']){
                    $discount = $relative_invoice_retailer['discount'];
                }
            }
        }

        //產品的出貨折扣
        $this->load->model('product_relationship_model');
        $relationship_products = $this->product_relationship_model->getRelationshipProducts($new_retailer_id, $new_shipout_retailer_id);

        //儲存產品
        $subtotal = 0;
        $total = 0;

        $this->load->model('purchase_item_model');
        $items = $purchase['items'];

        foreach ($items as $item) {
            $product_id = $item['product_id'];
            $qty = $item['qty'];
            $price = $item['price'];

            $item_discount = empty($relationship_products[$product_id]) ? $discount : $relationship_products[$product_id];

            $this->purchase_item_model->insert([
                'purchase_id' => $new_purchase_id,
                'product_id' => $product_id,
                'price' => $price,
                'qty' => $qty,
                'subtotal' => $price * $qty,
                'discount' => $item_discount,
                'total' => floor($price * $item_discount / 100) * $qty,
            ]);

            $subtotal += $price * $qty;
            $total += floor($price * $item_discount / 100) * $qty;
        }

        $this->purchase_model->update([
            'subtotal' => $subtotal,
            'total' => $total,
        ], ['id' => $new_purchase_id]);

        $this->load->model('payment_model');

        $this->payment_model->insert([
            'pay_type' => 'purchase',
            'pay_id' => $new_purchase_id,
            'paid_retailer_id' => $new_retailer_id,
            'received_retailer_id' => $new_shipout_retailer_id,
            'price' => $total,
            'retailer_id' => $dealer['retailer_id'],
            'dealer_id' => $dealer['id'],
            'active' => 0,
        ]);

        $this->purchase_model->update([
            'transfer_id' => $new_purchase_id,
        ], ['id' => $purchase_id]);

        return $new_purchase_id;
    }

    //計算銷貨折讓總額
    public function sumPurchaseAllowance($purchase_id)
    {
        $allowance_payment_total = 0;
        $this->load->model('payment_model');
        $payments = $this->payment_model
            ->where('pay_type', 'shipment_allowance')
            ->where('pay_id', $purchase_id)
            ->where('active', 1)
            ->where('isConfirmed', 1)
            ->get_all();
        if ($payments) {
            foreach ($payments as $payment){
                $allowance_payment_total += $payment['price'];
            }
        }

        return $allowance_payment_total;
    }
}

?>
<file_sep>/application/views/layout/blank.php
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="designer" content="cystudio, <EMAIL>" />
    <title><?= $title ?></title>
    <script src="<?= base_url('/js/jquery-3.2.1.slim.min.js')?>"></script>
    <script src="<?= base_url('/js/popper.min.js')?>"></script>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-M5LQ7CP');</script>
    <script src="<?= base_url('/js/bootstrap.min.js')?>"></script>
    <link href="<?= base_url('css/bootstrap.min.css') ?>" rel="stylesheet" type="text/css">
    <link href="<?= base_url('css/styles.css') ?>" rel="stylesheet" type="text/css">
</head>

<body>
<?php
if (isset($data)) {
    $this->load->view($view, $data);
} else {
    $this->load->view($view);
}
?>
</body>
</html><file_sep>/application/models/Order_return_model.php
<?php

class Order_return_model extends MY_Model
{
    public $table = 'olive_order_returns';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['items'] = array('Order_return_item_model', 'order_return_id', 'id');
        $this->has_one['dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'dealer_id');
    }
}

?>
<file_sep>/application/controllers/Commission.php
<?php

class Commission extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged())) {
            redirect(base_url('/'));
        }

        $this->load->model('dealer_model');
        $this->load->model('commission_model');
        $this->load->model('retailer_model');
        $this->load->model('retailer_relationship_model');

        $this->session->set_userdata('return_page', base_url('/commission/overview'));
    }

    //輔銷人列表
    public function dealers()
    {
        $_retailer_relationships = $this->retailer_relationship_model
            ->where('relation_retailer_id', $this->dealer['retailer_id'])
            ->where('relation_type', 'supervisor')
            ->get_all();
        $retailer_relationships = [];
        if ($_retailer_relationships){
            foreach ($_retailer_relationships as $retailer_relationship){
                array_push($retailer_relationships, $retailer_relationship['retailer_id']);
            }
        }

        $retailers = [];
        if ($retailer_relationships) {
            $total_retailers_count = $this->retailer_model
                ->where('id', $retailer_relationships)
                ->count_rows();

            $retailers = $this->retailer_model
                ->with_sales_retailer()
                ->with_sales_dealer()
                ->where('id', $retailer_relationships)
                ->paginate(20, $total_retailers_count);
        }

        $this->load->helper('data_format');

        //權限設定
        $authority = array();
        if ($this->authentic->authority('commission', 'dealer')){
            $authority['dealer'] = true;
        }

        $data = [
            'retailers' => $retailers,
            'authority' => $authority,
            'title' => '輔銷人名單',
            'view' => 'commission/dealers',
        ];

        $this->_preload($data);
    }

    public function dealer($dealer_id, $commissionMonth = '')
    {
//        $retailer_relationship = $this->retailer_relationship_model
//            ->where('retailer_id', $retailer_id)
//            ->where('relation_retailer_id', $this->dealer['retailer_id'])
//            ->where('relation_type', 'supervisor')
//            ->get();
//
//        if (!$retailer_relationship) {
//            show_error('查無輔銷人資料！');
//        }
//
//        $retailer = $this->retailer_model
//            ->with_sales_retailer()
//            ->with_sales_dealer()
//            ->get($retailer_id);

        $dealer = $this->dealer_model
            ->get($dealer_id);

        if (!$dealer) {
            show_error('查無輔銷人資料！');
        }

        $c = $this->commission_model
            ->fields('SUM(' . $this->commission_model->get_table_name() . '.total) as total')
            ->where('commission_type', 'dealer')
            ->where('commission_id', $dealer_id)
            ->get();
        $total_commission = $c['total'];

        if (!$commissionMonth) $commissionMonth = date('Y-m-d', strtotime('first day of previous month'));
        $first_day_commissionMonth = date('Y-m-01', strtotime($commissionMonth));
        $last_day_commissionMonth = date('Y-m-t', strtotime($commissionMonth));

        $_commissions = $this->commission_model
            ->with_purchase()
            ->where('commission_type', 'dealer')
            ->where('commission_id', $dealer_id)
            ->where('created_at', '>=', $first_day_commissionMonth)
            ->where('created_at', '<=', $last_day_commissionMonth)
            ->order_by($this->commission_model->get_table_name().'.created_at', 'desc')
            ->get_all();

        $month_total_commission = 0;
        $retailers = [];
        if ($_commissions){
            foreach ($_commissions as $commission) {
                $retailer_id = $commission['purchase']['retailer_id'];
                if (!isset($retailers[$retailer_id])){
                    $r = $this->retailer_model
                        ->with_sales_retailer()
                        ->with_sales_dealer()
                        ->get($retailer_id);
                    if ($r) {
                        $r['subtotal'] = 0;
                        $r['commissions'] = [];
                        $retailers[$retailer_id] = $r;
                    }
                }
                $retailers[$retailer_id]['subtotal'] += $commission['total'];
                $retailers[$retailer_id]['commissions'][] = $commission;
                $month_total_commission += $commission['total'];
            }
        }

        $commissionPrevMonth = date('Y-m-d', strtotime($commissionMonth . ' first day of previous month'));
        $commissionNextMonth = date('Y-m-d', strtotime($commissionMonth . ' first day of next month'));
        if (strtotime($commissionNextMonth) > time()){
            $commissionNextMonth = '';
        }

        $data = [
            'dealer' => $dealer,
            'retailers' => $retailers,
            'month_total_commission' => $month_total_commission,
            'total_commission' => $total_commission,
            'commissionMonth' => date('Y/m', strtotime($commissionMonth)),
            'prevMonthUrl' => base_url('/commission/dealer/' . $dealer_id . '/' . $commissionPrevMonth),
            'nextMonthUrl' => $commissionNextMonth ? base_url('/commission/dealer/' . $dealer_id . '/' . $commissionNextMonth) : '',
            'title' => '輔銷人獎金',
            'view' => 'commission/dealer',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/controllers/Capital_stock.php
<?php

class Capital_stock extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('stock_model');
        $this->load->model('retailer_model');
        $this->load->model('product_model');
        $this->load->helper('data_format');

        $this->session->set_userdata('return_page', base_url('/capital_stock/overview'));
    }

    public function overview($retailer_id = '')
    {
        $retailer_selects = $this->retailer_model->getRetailerSelect();

        $retailer = [];
        $products = [];
        if ($retailer_id) {
            $retailer = $this->retailer_model
                ->get($retailer_id);

            if (!$retailer){
                show_error('查無經銷單位資料');
            }
            $products = $this->product_model->getUnitProductStocks($retailer_id);
        }

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_stock', 'detail')){
            $authority['detail'] = true;
        }

        $data = [
            'retailer_id' => $retailer_id,
            'retailer_selects' => $retailer_selects,
            'retailer' => $retailer,
            'products' => $products,
            'authority' => $authority,
            'title' => '庫存列表',
            'view' => 'capital/stock/overview',
        ];

        $this->_preload($data);
    }

    public function detail($retailer_id, $product_id)
    {
        $retailer = $this->retailer_model
            ->get($retailer_id);

        if (!$retailer){
            show_error('查無經銷單位資料');
        }

        $product = $this->product_model
            ->with_pao()
            ->where('pKind', [3,6])
            ->where('pEnable', 'Y')
            ->where('pdId', $product_id)
            ->get();

        if (!$product_id || !$product) {
            show_error('查無經銷單位商品資料！');
        }

        $stocks = $this->stock_model
            ->where('product_id', $product['pdId'])
            ->where('retailer_id', $retailer_id)
            ->where('stock', '>', 0)
            ->order_by('expired_at', 'asc')
            ->get_all();

        $product['stock'] = $this->product_model->calcStock($stocks, $product);

        $data = [
            'retailer' => $retailer,
            'product' => $product,
            'title' => '詳細產品庫存資訊',
            'view' => 'capital/stock/detail',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/controllers/Income.php
<?php

class Income extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged())) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_model');
        $this->load->model('dealer_model');
        $this->load->model('commission_model');
        $this->load->model('payment_model');
        $this->load->model('expense_model');

        $this->session->set_userdata('return_page', base_url('/capital_income/overview'));
    }

    public function overview()
    {
        $this->load->model('retailer_relationship_model');
        $retailers = $this->retailer_relationship_model
            ->with_retailer()
            ->where('relation_retailer_id', $this->dealer['retailer_id'])
            ->where('relation_type', 'supervisor')
            ->get_all();

        $search = array(
            'retailer_id' => (int)$this->input->get('retailer_id'),
            'created_start' => strtotime($this->input->get('created_start')) > 0 ? $this->input->get('created_start') : date('Y-m-01'),
            'created_end' => strtotime($this->input->get('created_end')) > 0 ? $this->input->get('created_end') : date('Y-m-t'),
        );

        if ($search['retailer_id']){
            $retailer_relationship = $this->retailer_relationship_model
                ->where('retailer_id', $search['retailer_id'])
                ->where('relation_retailer_id', $this->dealer['retailer_id'])
                ->where('relation_type', 'supervisor')
                ->get();
            if (!$retailer_relationship){
                show_error('查無單位資料！');
            }
            $retailer_id = $search['retailer_id'];
        } else {
            $retailer_id = $this->dealer['retailer_id'];
        }

        $income = [
            'revenue' => [],
            'expense' => [],
            'total' => 0,
        ];

        if ($retailer_id) {
            $payment_table = $this->payment_model->get_table_name();
            //出貨收益
            $data = $this->payment_model
                ->fields('SUM(' . $payment_table . '.price) as total')
                ->where('received_retailer_id', $retailer_id)
                ->where('pay_type', 'purchase')
                ->where('isConfirmed', 1)
                ->where('created_at', '<=', $search['created_end'])
                ->where('created_at', '>=', $search['created_start'])
                ->get();

            if (!empty($data['total'])) {
                $income['revenue'][] = [
                    'name' => '出貨收益',
                    'total' => $data['total']
                ];
                $income['total'] += $data['total'];
            }

            //進貨銷貨折讓
            $data = $this->payment_model
                ->fields('SUM(' . $payment_table . '.price) as total')
                ->where('received_retailer_id', $retailer_id)
                ->where('pay_type', 'shipment_allowance')
                ->where('isConfirmed', 1)
                ->where('created_at', '<=', $search['created_end'])
                ->where('created_at', '>=', $search['created_start'])
                ->get();

            if (!empty($data['total'])) {
                $income['revenue'][] = [
                    'name' => '進貨銷貨折讓',
                    'total' => $data['total']
                ];
                $income['total'] += $data['total'];
            }

            //消費者訂單收益
            $data = $this->payment_model
                ->fields('SUM(' . $payment_table . '.price) as total')
                ->where('received_retailer_id', $retailer_id)
                ->where('pay_type', 'order')
                ->where('isConfirmed', 1)
                ->where('created_at', '<=', $search['created_end'])
                ->where('created_at', '>=', $search['created_start'])
                ->get();

            if (!empty($data['total'])) {
                $income['revenue'][] = [
                    'name' => '消費者訂購',
                    'total' => $data['total']
                ];
                $income['total'] += $data['total'];
            }

            //輔銷獎金收益
            $data = $this->commission_model
                ->fields('SUM(' . $this->commission_model->get_table_name() . '.total) as total')
                ->where('commission_type', 'retailer')
                ->where('commission_id', $retailer_id)
                ->where('created_at', '<=', $search['created_end'])
                ->where('created_at', '>=', $search['created_start'])
                ->get();
            if (!empty($data['total'])) {
                $income['revenue'][] = [
                    'name' => '輔銷獎金收益',
                    'total' => $data['total']
                ];
                $income['total'] += $data['total'];
            }

            //進貨支出
            $data = $this->payment_model
                ->fields('SUM(' . $payment_table . '.price) as total')
                ->where('paid_retailer_id', $retailer_id)
                ->where('pay_type', 'purchase')
                ->where('isConfirmed', 1)
                ->where('created_at', '<=', $search['created_end'])
                ->where('created_at', '>=', $search['created_start'])
                ->get();
            if (!empty($data['total'])) {
                $income['expense'][] = [
                    'name' => '進貨支出',
                    'total' => $data['total']
                ];
                $income['total'] -= $data['total'];
            }

            //出貨銷貨折讓
            $data = $this->payment_model
                ->fields('SUM(' . $payment_table . '.price) as total')
                ->where('paid_retailer_id', $retailer_id)
                ->where('pay_type', 'shipment_allowance')
                ->where('isConfirmed', 1)
                ->where('created_at', '<=', $search['created_end'])
                ->where('created_at', '>=', $search['created_start'])
                ->get();
            if (!empty($data['total'])) {
                $income['expense'][] = [
                    'name' => '出貨銷貨折讓',
                    'total' => $data['total']
                ];
                $income['total'] -= $data['total'];
            }

            //輔銷獎金支出
            $sales_retailers = $this->retailer_model
                ->where('sales_retailer_id', $retailer_id)
                ->get_all();
            $sales_dealers = [];
            if ($sales_retailers) {
                foreach ($sales_retailers as $sales_retailer) {
                    array_push($sales_dealers, $sales_retailer['sales_dealer_id']);
                }
            }
            if ($sales_dealers) {
                $data = $this->commission_model
                    ->fields('SUM(' . $this->commission_model->get_table_name() . '.total) as total')
                    ->where('commission_type', 'dealer')
                    ->where('commission_id', $sales_dealers)
                    ->where('created_at', '<=', $search['created_end'])
                    ->where('created_at', '>=', $search['created_start'])
                    ->get();
                if (!empty($data['total'])) {
                    $income['expense'][] = [
                        'name' => '輔銷獎金支出',
                        'total' => $data['total']
                    ];
                    $income['total'] -= $data['total'];
                }
            }

            //運費支出
            $data = $this->expense_model
                ->fields('SUM(' . $this->expense_model->get_table_name() . '.price) as total')
                ->where('retailer_id', $retailer_id)
                ->where('expense_type', 'freight')
                ->where('created_at', '<=', $search['created_end'])
                ->where('created_at', '>=', $search['created_start'])
                ->get();
            if (!empty($data['total'])) {
                $income['expense'][] = [
                    'name' => '運費支出',
                    'total' => $data['total']
                ];
                $income['total'] -= $data['total'];
            }

            //手續費
            $data = $this->expense_model
                ->fields('SUM(' . $this->expense_model->get_table_name() . '.price) as total')
                ->where('retailer_id', $retailer_id)
                ->where('expense_type', 'fare')
                ->where('created_at', '<=', $search['created_end'])
                ->where('created_at', '>=', $search['created_start'])
                ->get();
            if (!empty($data['total'])) {
                $income['expense'][] = [
                    'name' => '手續費支出',
                    'total' => $data['total']
                ];
                $income['total'] -= $data['total'];
            }
        }

        $data = [
            'search' => $search,
            'income' => $income,
            'retailers' => $retailers,
            'title' => '營業資訊',
            'view' => 'income/overview',
        ];

        $this->_preload($data);
    }

    public function product()
    {
        $this->load->model('retailer_relationship_model');
        $retailers = $this->retailer_relationship_model
            ->with_retailer()
            ->where('relation_retailer_id', $this->dealer['retailer_id'])
            ->where('relation_type', 'supervisor')
            ->get_all();

        $search = array(
            'retailer_id' => (int)$this->input->get('retailer_id'),
            'product_id' => (int)$this->input->get('product_id'),
            'created_start' => strtotime($this->input->get('created_start')) > 0 ? $this->input->get('created_start') : date('Y-m-01'),
            'created_end' => strtotime($this->input->get('created_end')) > 0 ? $this->input->get('created_end') : date('Y-m-t'),
        );

        if ($search['retailer_id']){
            $retailer = $this->retailer_relationship_model
                ->where('retailer_id', $search['retailer_id'])
                ->where('relation_retailer_id', $this->dealer['retailer_id'])
                ->where('relation_type', 'supervisor')
                ->get();
            if (!$retailer){
                show_error('查無單位資料！');
            }
            $retailer_id = $search['retailer_id'];
        } else {
            $retailer_id = $this->dealer['retailer_id'];
        }

        $income = [
            'revenue' => [],
            'expense' => [],
            'totalQty' => 0,
            'total' => 0,
        ];

        if ($retailer_id && $search['product_id']) {
            $this->load->model('purchase_model');
            $this->load->model('purchase_item_model');
            $purchase_item_table = $this->purchase_item_model->get_table_name();

            $purchases = $this->purchase_model
                ->with_items(['where' => "product_id='". $search['product_id'] . "'", 'fields' => 'SUM(' . $purchase_item_table . '.qty) as totalQty, SUM(' . $purchase_item_table . '.total) as total'])
                ->where('shipout_retailer_id', $retailer_id)
                ->where('isShipConfirmed', 1)
                ->where('created_at', '<=', $search['created_end'])
                ->where('created_at', '>=', $search['created_start'])
                ->get_all();
            if (!empty($purchases)) {
                foreach ($purchases as $purchase){
                    $income['revenue'][] = [
                        'name' => '出貨售出',
                        'totalQty' => $purchase['items'][0]['totalQty'],
                        'total' => $purchase['items'][0]['total'],
                    ];
                    $income['totalQty'] += $purchase['items'][0]['totalQty'];
                    $income['total'] += $purchase['items'][0]['total'];
                }
            }


            $purchases = $this->purchase_model
                ->with_items(['where' => "product_id='". $search['product_id'] . "'", 'fields' => 'SUM(' . $purchase_item_table . '.qty) as totalQty, SUM(' . $purchase_item_table . '.total) as total'])
                ->where('shipin_retailer_id', $retailer_id)
                ->where('isShipConfirmed', 1)
                ->where('created_at', '<=', $search['created_end'])
                ->where('created_at', '>=', $search['created_start'])
                ->get_all();
            if (!empty($purchases)) {
                foreach ($purchases as $purchase){
                    $income['revenue'][] = [
                        'name' => '進貨購入',
                        'totalQty' => $purchase['items'][0]['totalQty'],
                        'total' => $purchase['items'][0]['total'],
                    ];
                    $income['totalQty'] -= $purchase['items'][0]['totalQty'];
                    $income['total'] -= $purchase['items'][0]['total'];
                }
            }


            $this->load->model('order_model');
            $this->load->model('order_item_model');
            $order_item_table = $this->order_item_model->get_table_name();

            $orders = $this->order_model
                ->with_items(['where' => "product_id='". $search['product_id'] . "'", 'fields' => 'SUM(' . $order_item_table . '.qty) as totalQty, SUM(' . $order_item_table . '.subPrice) as total'])
                ->where('shipout_retailer_id', $retailer_id)
                ->where('isConfirmed', 1)
                ->where('created_at', '<=', $search['created_end'])
                ->where('created_at', '>=', $search['created_start'])
                ->get_all();
            if (!empty($orders)) {
                foreach ($orders as $order){
                    $income['revenue'][] = [
                        'name' => '消費者訂購',
                        'totalQty' => $order['items'][0]['totalQty'],
                        'total' => $order['items'][0]['total'],
                    ];
                    $income['totalQty'] += $order['items'][0]['totalQty'];
                    $income['total'] += $order['items'][0]['total'];
                }
            }
        }

        $this->load->model('product_model');
        $products = $this->product_model->getCustomerProducts();

        $data = [
            'search' => $search,
            'income' => $income,
            'retailers' => $retailers,
            'products' => $products,
            'title' => '產品業績',
            'view' => 'income/product',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/libraries/Purchase_lib.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Purchase_lib
{
    var $CI;
    var $purchase = [];

    public function __construct($purchase=[])
    {
        $this->CI =& get_instance();
        $this->purchase = $purchase;

        $this->CI->load->model('purchase_model');
        $this->CI->load->model('retailer_relationship_model');
        $this->CI->load->helper('data_format');
    }

    //取得經銷商訂購紀錄
    public function getRetailerTotalPurchases($retailer_id, $end_day = null)
    {
        $total = 0;
        $count = 0;
        $first_at = null;
        $first_total = 0;

        if (!is_null($end_day)){
            $this->CI->purchase_model->where('created_at', '<', $end_day);
        }

        $first_purchase = $this->CI->purchase_model
            ->where('retailer_id', $retailer_id)
            ->where('isConfirmed', 1)
            ->order_by('created_at', 'asc')
            ->get();

        if ($first_purchase){
            $first_at = $first_purchase['created_at'];
            $first_total = $first_purchase['subtotal'];

            $table = $this->CI->purchase_model->get_table_name();

            $purchase = $this->CI->purchase_model
                ->fields('SUM(' . $table . '.subtotal) as total, COUNT(' . $table . '.id) AS counted_rows')
                ->where('retailer_id', $retailer_id)
                ->where('isConfirmed', 1)
                ->get();
            if ($purchase){
                $total = $purchase['total'];
                $count = $purchase['counted_rows'];
            }
        }

        return [
            'count' => $count,
            'total' => $total,
            'first_at' => $first_at,
            'first_total' => $first_total,
        ];
    }

    //訂貨單確認
    public function generateConfirmLabel($showMemo = false)
    {
        $string = '';
        if (is_null($this->purchase['isConfirmed'])){
            $string .= '<span class="badge badge-warning">待回覆</span>';
        } else {
            $confirm = isset($this->purchase['confirm']) ? $this->purchase['confirm'] : [];
            if ($confirm) {
                $string .= confirmStatus($confirm['audit'], $confirm['memo']);
                if ($showMemo) {
                    $string .= '<div>' . nl2br($confirm['memo']) . '</div>';
                }
            }
        }

        return $string;
    }

    //收付款狀態
    public function generatePaidLabel($showMemo = false)
    {
        $string = eventStatus($this->purchase['isPaid']);
        if ($this->purchase['isPaid'] && !$this->purchase['isPayConfirmed']){
            $string .= ' <span class="badge badge-warning">待確認</span>';
        }

        return $string;
    }

    //出貨狀態
    public function generateShippedLabel()
    {
        $string = eventStatus($this->purchase['isShipped']);
        if ($this->purchase['isShipped'] && !$this->purchase['isShipConfirmed']){
            $string .= ' <span class="badge badge-warning">待確認</span>';
        }

        return $string;
    }

    public function getShipOutList($retailer_id)
    {
        $_retailers = $this->CI->retailer_relationship_model
            ->with_relation()
            ->where('relation_type', 'shipout')
            ->where('retailer_id', $retailer_id)
            ->get_all();

        $retailers = [];
        if ($_retailers){
            foreach ($_retailers as $r){
                $retailers[$r['relation_retailer_id']] = [
                    'id' => $r['relation_retailer_id'],
                    'company' => $r['relation']['company'],
                    'invoice_title' => $r['relation']['invoice_title'],
                    'discount' => $r['discount'],
                    'hasStock' => $r['relation']['hasStock'],
                ];
            }
        }

        return $retailers;
    }

    public function getShipOutListReverse($retailer_id)
    {
        $_retailers = $this->CI->retailer_relationship_model
            ->with_retailer()
            ->where('relation_type', 'shipout')
            ->where('relation_retailer_id', $retailer_id)
            ->get_all();

        $retailers = [];
        if ($_retailers){
            foreach ($_retailers as $r){
                $retailers[$r['retailer_id']] = [
                    'id' => $r['retailer_id'],
                    'company' => $r['retailer']['company'],
                    'invoice_title' => $r['retailer']['invoice_title'],
                ];
            }
        }

        return $retailers;
    }

    public function getShipInList($retailer_id, $shipout_retailer_id)
    {
        $_retailers = $this->CI->retailer_relationship_model
            ->with_alter()
            ->where('relation_type', 'shipin')
            ->where('retailer_id', $retailer_id)
            ->where('relation_retailer_id', $shipout_retailer_id)
            ->get_all();

        $retailers = [];
        if ($_retailers){
            foreach ($_retailers as $r){
                $data = [
                    'id' => $r['alter_retailer_id'],
                    'company' => $r['alter']['company'],
                    'invoice_title' => $r['alter']['invoice_title'],
                    'retailer_role_id' => $r['alter']['retailer_role_id'],
                    'address' => $r['alter']['address'],
                    'purchaseThreshold' => $r['alter']['purchaseThreshold'],
                    'hasStock' => $r['alter']['hasStock'],
                    'level' => [],
                ];

                if (!empty($r['retailer_level_id'])) {
                    $retailer_level = $this->retailer_level_model->get($r['retailer_level_id']);
                    if ($retailer_level) {
                        $data['level'] = [
                            'firstThreshold' => $retailer_level['firstThreshold'],
                            'monthThreshold' => $retailer_level['monthThreshold'],
                        ];
                    }
                }

                $retailers[$r['alter_retailer_id']] = $data;
            }
        }

        return $retailers;
    }

    public function getInvoiceList($retailer_id, $shipout_retailer_id)
    {
        $_retailers = $this->CI->retailer_relationship_model
            ->with_alter()
            ->where('relation_type', 'invoice')
            ->where('retailer_id', $retailer_id)
            ->where('relation_retailer_id', $shipout_retailer_id)
            ->get_all();

        $retailers = [];
        if ($_retailers){
            foreach ($_retailers as $r){
                $retailers[$r['alter_retailer_id']] = [
                    'id' => $r['alter_retailer_id'],
                    'company' => $r['alter']['company'],
                    'invoice_title' => $r['alter']['invoice_title'],
                    'discount' => $r['discount'],
                ];
            }
        }

        return $retailers;
    }

    public function getInvoiceSendList($retailer_id)
    {
        $_retailers = $this->CI->retailer_relationship_model
            ->with_relation()
            ->where('relation_type', 'invoice_send')
            ->where('retailer_id', $retailer_id)
            ->get_all();

        $retailers = [];
        if ($_retailers){
            foreach ($_retailers as $r){
                $retailers[$r['relation_retailer_id']] = [
                    'id' => $r['relation_retailer_id'],
                    'company' => $r['relation']['company'],
                    'invoice_title' => $r['relation']['invoice_title'],
                    'address' => $r['relation']['address'],
                ];
            }
        }

        return $retailers;
    }

    //計算月份差
    public function get_month_diff($start, $end = FALSE)
    {
        if (!$end) $end = date('Y-m-d');

        $start_year = date('Y', strtotime($start));
        $start_month = date('m', strtotime($start));

        $end_year = date('Y', strtotime($end));
        $end_month = date('m', strtotime($end));

        if ($end_month < $start_month){
            $end_year--;
            $end_month += 12;
        }

        return ($end_year - $start_year) * 12 + $end_month - $start_month;
    }
}

?><file_sep>/application/views/capital/promote/method/add.php
<div class="container">
    <h1 class="mb-4"><?= $promote['title'] ?>優惠方式設定</h1>

    <form method="post">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group">
            <label class="font-weight-bold">優惠方式</label>
            <?php
            echo form_dropdown('promote_type_id', ['' => ''] + $promote_type, '', 'id="promote_type_id" class="form-control" required');
            ?>
        </div>
    </form>

</div>

<script>
    $().ready(function () {
        $('#promote_type_id').change(function () {
            var promote_type_id = parseInt($(this).val()) || 0;
            if (promote_type_id > 0) {
                window.location = '<?=base_url('capital_promote_method/add/' . $promote['id'] . '/') ?>' + promote_type_id;
            }
        });
    });
</script><file_sep>/application/views/consumer/index.php
<div class="container">
    <div class="justify-content-md-center d-flex align-items-center" style="height: 75vh;">
        <?php if (!empty($authority['customer'])){ ?>
        <a href="<?=base_url('/customer/overview')?>" class="btn btn-success mr-4">個人歷史消費紀錄</a>
        <?php } ?>
        <?php if (!empty($authority['consumer'])){ ?>
        <a href="<?=base_url('/consumer/overview')?>" class="btn btn-success mr-4">銷售單位歷史銷售</a>
        <?php } ?>
        <?php if (!empty($authority['coupon'])){ ?>
        <a href="<?=base_url('/coupon/overview')?>" class="btn btn-success">貴賓優惠券序號登錄</a>
        <?php } ?>
    </div>
</div><file_sep>/application/views/consumer/transfer.php
<div class="container">
    <h1 class="mb-4">A店買B店取貨之紀錄</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">日期</th>
            <th class="text-center">取貨人</th>
            <th class="text-center">電話</th>
            <th class="text-center">售出單位</th>
            <th class="text-center">取貨單位</th>
            <th class="text-center">新增進貨單</th>
            <th class="text-center">開立取貨單</th>
            <th class="text-center">是否取貨</th>
            <th class="text-center"></th>
        </tr>
        <?php
        if ($transfers) {
            foreach ($transfers as $transfer) {
                ?>
                <tr>
                    <td class="text-center"><?= date('Y-m-d', strtotime($transfer['created_at'])) ?></td>
                    <td class="text-center"><?= !empty($transfer['order']['contact']['name']) ? $transfer['order']['contact']['name'] : '' ?></td>
                    <td class="text-center"><?= !empty($transfer['order']['contact']['phone']) ? $transfer['order']['contact']['phone'] : '' ?></td>
                    <td class="text-center"><?= $transfer['retailer']['company'] ?></td>
                    <td class="text-center"><?= $transfer['shipout_retailer']['company'] ?></td>
                    <td class="text-center"><?= yesno($transfer['purchase_id']) ?></td>
                    <td class="text-center"><?= yesno($transfer['isRecorded']) ?></td>
                    <td class="text-center"><?= yesno($transfer['isDeliveried']) ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php if ($transfer['retailer_id'] == $dealer['retailer_id'] && !$transfer['isRecorded'] && !empty($authority['transfer_record'])){ ?>
                                <a class="btn btn-warning btn-sm" href="<?= base_url('/consumer/transfer_record/' . $transfer['id']) ?>">
                                    已開立取貨單
                                </a>
                            <?php } ?>

                            <?php if ($transfer['shipout_retailer_id'] == $dealer['retailer_id'] && $transfer['isRecorded'] && !$transfer['isDeliveried'] && !empty($authority['transfer_delivery'])){ ?>
                                <a class="btn btn-warning btn-sm" href="<?= base_url('/consumer/transfer_delivery/' . $transfer['id']) ?>">
                                    確認取貨
                                </a>
                            <?php } ?>

                            <?php if (!empty($authority['detail'])){ ?>
                            <a class="btn btn-info btn-sm" href="<?= base_url('/consumer/detail/' . $transfer['order_id']) ?>">
                                <i class="fas fa-search"></i> 明細
                            </a>
                            <?php } ?>
                        </div>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="9" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div><file_sep>/application/migrations/008_add_payment.php
<?php
//經銷商訂貨單產品
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_payment extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'pay_type' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => TRUE,
            ],
            'pay_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'paid_retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'received_retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'price' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'receipt' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
            ],
            'memo' => [
                'type' => 'TEXT',
                'null' => TRUE,
            ],
            'isConfirmed' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'dealer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_payments');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_payments');
    }
}<file_sep>/application/controllers/Capital_combo.php
<?php

class Capital_combo extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('combo_model');
        $this->load->model('combo_item_model');

        $this->session->set_userdata('return_page', base_url('/capital_combo/overview'));
    }

    public function overview()
    {
        $total_combos_count = $this->combo_model
            ->count_rows();

        $combos = $this->combo_model
            ->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
            ->order_by('id', 'desc')
            ->paginate(20, $total_combos_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_combo', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('capital_combo', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('capital_combo', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'combos' => $combos,
            'pagination' => $this->combo_model->all_pages,
            'authority' => $authority,
            'title' => '商品組合列表',
            'view' => 'capital/combo/overview',
        ];

        $this->_preload($data);
    }

    public function add()
    {
        $this->load->model('product_model');
        $products = $this->product_model->getCustomerProducts();

        if ($this->input->post()) {
            $this->form_validation->set_rules('name', '組合名稱', 'required|max_length[100]');
            $this->form_validation->set_rules('items[][price]', '產品金額', 'callback_check_total[' . json_encode(['products' => $products, 'items' => $this->input->post('items')]) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $combo_id = $this->combo_model->insert([
                    'name' => $this->input->post('name'),
                ]);

                $items = (array)$this->input->post('items');
                $total = 0;
                foreach ($items as $product_id => $item) {
                    $this->combo_item_model->insert([
                        'combo_id' => $combo_id,
                        'product_id' => $product_id,
                        'price' => $item['price'],
                        'qty' => $item['qty'],
                    ]);
                    $total += $item['price'] * $item['qty'];
                }

                $this->combo_model->update([
                    'total' => $total,
                ], ['id' => $combo_id]);

                redirect(base_url('/capital_combo/overview/'));
            }
        }

        $this->load->helper('form');

        $data = [
            'products' => $products,
            'title' => '新增商品組合',
            'view' => 'capital/combo/add',
        ];

        $this->_preload($data);
    }

    public function edit($combo_id)
    {
        $combo = $this->combo_model
            ->with_items()
            ->get($combo_id);

        if (!$combo_id || !$combo) {
            show_error('查無商品組合資料');
        }

        $this->load->model('product_model');
        $products = $this->product_model->getCustomerProducts();

        if ($this->input->post()) {
            $this->form_validation->set_rules('name', '組合名稱', 'required|max_length[100]');
            $this->form_validation->set_rules('items[][price]', '產品金額', 'callback_check_total[' . json_encode(['products' => $products, 'items' => $this->input->post('items')]) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $this->combo_model->update([
                    'name' => $this->input->post('name'),
                ], ['id' => $combo_id]);

                $this->combo_item_model->where('combo_id', $combo_id)->delete();

                $items = (array)$this->input->post('items');
                $total = 0;
                foreach ($items as $product_id => $item) {
                    $this->combo_item_model->insert([
                        'combo_id' => $combo_id,
                        'product_id' => $product_id,
                        'price' => $item['price'],
                        'qty' => $item['qty'],
                    ]);
                    $total += $item['price'] * $item['qty'];
                }

                $this->combo_model->update([
                    'total' => $total,
                ], ['id' => $combo_id]);

                redirect(base_url('/capital_combo/overview/'));
            }
        }

        $_items = $combo['items'];
        $items = [];
        foreach ($_items as $item){
            $items[$item['product_id']] = $item;
        }

        $data = [
            'products' => $products,
            'combo' => $combo,
            'items' => $items,
            'title' => '編輯商品組合',
            'view' => 'capital/combo/edit',
        ];

        $this->_preload($data);
    }

    public function check_total($i, $params)
    {
        $params = json_decode($params, true);

        $products = $params['products'];
        $items = $params['items'];
        $totalQty = 0;
        $error = '';

        foreach ($items as $product_id => $item) {
            if (!isset($products[$product_id])) {
                $error = '輸入的貨品有誤';
                break;
            }

            if ((!$item['price'] && $item['price'] !== '0') || !$item['qty']) {
                $error = '數量與組合分攤單價必須填寫';
                break;
            }

            $totalQty += $item['qty'];
        }

        if ($totalQty < 2){
            $error = '商品組合至少要有兩樣產品';
        }

        if (!$error) {
            return true;
        } else {
            $this->form_validation->set_message('check_total', $error);
            return false;
        }
    }

    public function cancel($combo_id)
    {
        $combo = $this->combo_model
            ->get($combo_id);

        if (!$combo_id || !$combo) {
            show_error('查無商品組合資料');
        }

        $this->combo_model->delete($combo_id);

        redirect(base_url('/capital_combo/overview/'));
    }
}

?><file_sep>/application/migrations/016_add_recommend.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_recommend extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'type' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => 'I'
            ],
            'content' => [
                'type' => 'text'
            ],
            'isConfirmed' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_recommend_templates');

        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'recommend_template_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'picture1' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
            ],
            'picture2' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
            ],
            'picture3' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
            ],
            'isTemp' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_recommends');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_recommend_templates');
        $this->dbforge->drop_table('olive_recommends');
    }
}<file_sep>/application/models/Free_package_item_model.php
<?php

class Free_package_item_model extends MY_Model
{
    public $table = 'olive_free_package_items';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['product'] = array('foreign_model'=>'Product_model','foreign_table'=>'product','foreign_key'=>'pdId','local_key'=>'product_id');
    }
}

?>
<file_sep>/application/libraries/Customer_lib.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Customer_lib
{
    var $CI;
    var $customer_id = '';
    var $customer = [];

    public function __construct()
    {
        $this->CI =& get_instance();

        $this->CI->load->model('customer_model');
        $this->CI->load->model('customer_level_model');
        $this->CI->load->model('order_model');
        $this->CI->load->model('customer_level_history_model');

    }

    public function setCustomerID($customer_id)
    {
        $this->customer_id = $customer_id;
        $this->setCustomer();
    }

    public function setCustomer()
    {
        $this->customer = $this->CI->customer_model
            ->with_level()
            ->get($this->customer_id);
    }

    public function getCustomer()
    {
        return $this->customer;
    }

    public function getCustomerLevels()
    {
        return $this->CI->customer_level_model->get_all();
    }

    public function downgradeCheckByPhone($phone)
    {
        $customers = $this->CI->customer_model
            ->with_level()
            ->where('phone', $phone)
            ->get_all();
        if ($customers) {
            foreach ($customers as $customer) {
                $this->customer_id = $customer['id'];
                $this->customer = $customer;
                $this->downgradeCheckCustomerLevel();
            }
        }
    }

    //檢查降級狀態
    public function downgradeCheckCustomerLevel()
    {
        $isChange = false;
        if ($this->customer && !$this->customer['isDealer']) {
            if (!is_null($this->customer['old_customer_id'])) { //舊會員才會降級
                if ($this->customer['customer_level_id'] == 2) {
                    $count = $this->getCountOrderOfYear(1);
                    $total = $this->getLargestPriceOrderOfYear();
                    if ($count > 0 && $count < 12 && $total < 12000) {
                        $this->CI->customer_model->update([
                            'customer_level_id' => 1,
                        ], ['id' => $this->customer_id]);

                        $this->saveLevelChangeHistory(1, 1);

                        $isChange = true;
                    }
                }

                $count = $this->getCountOrderOfYear(2);
                if (!$count) {
                    $this->CI->customer_model->update([
                        'customer_level_id' => null,
                    ], ['id' => $this->customer_id]);

                    $this->saveLevelChangeHistory(null, 1);
                    $isChange = true;
                }
            }
        }

        //重新整理
        if ($isChange) {
            $this->setCustomer();
        }
        return;
    }

    protected function getCountOrderOfYear($year = 1)
    {
        $firstTime = $this->customFirstTime();
        if ($firstTime) {
            $check_start_date = date("Y-m-d", strtotime($firstTime['created_at']));
            $check_end_date = date("Y-m-d", strtotime($check_start_date . " + " . $year . " year"));

            return $this->CI->order_model
                ->where('buyer_type', 'customer')
                ->where('buyer_id', $this->customer['id'])
                ->where('created_at', '>=', $check_start_date)
                ->where('created_at', '<', $check_end_date)
                ->count_rows();
        }

        return true;
    }

    protected function getLargestPriceOrderOfYear()
    {
        $firstTime = $this->customFirstTime();
        if ($firstTime) {
            $check_start_date = date("Y-m-d", strtotime($firstTime['created_at']));
            $check_end_date = date("Y-m-d", strtotime($check_start_date . " + 1 year"));

            return $this->CI->order_model
                ->where('buyer_type', 'customer')
                ->where('buyer_id', $this->customer['id'])
                ->where('created_at', '>=', $check_start_date)
                ->where('created_at', '<', $check_end_date)
                ->order_by('total', 'desc')
                ->get();
        }

        return true;
    }

    //升級規則
    public function upgradeLevel()
    {
        if (!$this->customer || $this->customer['isDealer']) return false;

        if (empty($this->customer['customer_level_id'])) {
            $customer_level_id = null;
        } else {
            $customer_level_id = intval($this->customer['customer_level_id']);
        }

        $level = false;
        switch ($customer_level_id) {
            case 1:
                $level = $this->upgradeLevel2Rule();
                break;
            case 2:
                $level = $this->upgradeLevel3Rule();
                break;
            case 3:
                break;
            default:
                $level = $this->upgradeLevel1Rule();
                break;
        }

        return $level;
    }

    //消費者第一次購買日期
    protected function customFirstTime()
    {
        $order_data = $this->CI->order_model
            ->where('buyer_type', 'customer')
            ->where('buyer_id', $this->customer_id)
            ->where('isConfirmed', 1)
            ->where('isPaid', 1)
            ->where('isShipped', 1)
            ->order_by('created_at', 'asc')
            ->get();
        if ($order_data) {
            return $order_data;
        }
        return false;
    }

    protected function upgradeLevel1Rule()
    {
        $rule = [
            'once' => 12000,
            'year' => 20000,
        ];

        $level = false;

        $accountYearRange = $this->getAccountYearRange();

        $orders = $this->CI->order_model
            ->where('buyer_type', 'customer')
            ->where('buyer_id', $this->customer_id)
            ->where('created_at', '>=', $accountYearRange['start'])
            ->where('created_at', '<=', $accountYearRange['end'])
            ->order_by('total', 'desc')
            ->get();

        if ($orders && $orders['total'] >= $rule['once']) {
            $level = 1;
        }

        if (!$level) {
            $table = $this->CI->order_model->get_table_name();

            $orders = $this->CI->order_model
                ->fields('SUM(' . $table . '.total) as total')
                ->where('buyer_type', 'customer')
                ->where('buyer_id', $this->customer_id)
                ->where('created_at', '>=', $accountYearRange['start'])
                ->where('created_at', '<=', $accountYearRange['end'])
                ->get();
            if ($orders && $orders['total'] >= $rule['year']) {
                $level = 1;
            }
        }

        return $level;
    }

    protected function upgradeLevel2Rule()
    {
        $rule = [
            'count' => 6,
        ];

        $level = false;

        $accountYearRange = $this->getAccountYearRange();

        //本年度消費次數
        $total_orders_count = $this->CI->order_model
            ->where('buyer_type', 'customer')
            ->where('buyer_id', $this->customer_id)
            ->where('created_at', '>=', $accountYearRange['start'])
            ->where('created_at', '<=', $accountYearRange['end'])
            ->count_rows();

        if ($total_orders_count >= $rule['count']) {
            $level = 2;
        }

        return $level;
    }

    protected function upgradeLevel3Rule()
    {
        $rule = [
            'count' => 20,
            'year' => 330000,
        ];

        $level = false;

        $accountYearRange = $this->getAccountYearRange();

        //本年度消費次數
        $total_orders_count = $this->CI->order_model
            ->where('buyer_type', 'customer')
            ->where('buyer_id', $this->customer_id)
            ->where('created_at', '>=', $accountYearRange['start'])
            ->where('created_at', '<=', $accountYearRange['end'])
            ->count_rows();

        if ($total_orders_count >= $rule['count']) {
            //本年度消費總額
            $table = $this->CI->order_model->get_table_name();
            $orders = $this->CI->order_model
                ->fields('SUM(' . $table . '.total) as total')
                ->where('buyer_type', 'customer')
                ->where('buyer_id', $this->customer_id)
                ->where('created_at', '>=', $accountYearRange['start'])
                ->where('created_at', '<=', $accountYearRange['end'])
                ->get();

            if ($orders && $orders['total'] >= $rule['year']) {
                $level = 3;
            }
        }

        return $level;
    }

    public function saveLevelChangeHistory($customer_level_id, $isConfirmed = false)
    {
        if (!$this->customer || $this->customer['isDealer']) return false;

        $this->CI->customer_level_history_model->insert([
            'customer_id' => $this->customer['id'],
            'old_customer_level_id' => empty($this->customer['customer_level_id']) ? null : $this->customer['customer_level_id'],
            'new_customer_level_id' => $customer_level_id,
            'isConfirmed' => $isConfirmed,
        ]);
    }

    //年度的計算時間改為  “每年8月1日至次年7月31日”為一年度
    public function getAccountYearRange()
    {
        $y = date('Y');
        $m = date('m');
        if ($m < 8){
            return [
                'start' => ($y-1) . '-8-1',
                'end' => $y . '-7-31',
            ];
        } else {
            return [
                'start' => $y . '-8-1',
                'end' => ($y+1) . '-7-31',
            ];
        }
    }

    public function getCurrentSeasonRange()
    {
        $time = time();
        $year = date('Y', $time);
        $month = date('m', $time);

        if ($month < 4){
            return [
                $year . '-01-01',
                $year . '-03-31',
            ];
        } elseif ($month < 7){
            return [
                $year . '-04-01',
                $year . '-06-30',
            ];
        } elseif ($month < 10){
            return [
                $year . '-07-01',
                $year . '-09-30',
            ];
        } else {
            return [
                $year . '-10-01',
                $year . '-12-31',
            ];
        }
    }
}

?><file_sep>/application/views/payment/confirm.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">確認收款作業</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>
                <div class="form-group">
                    <label class="font-weight-bold">付款金額</label>
                    <div>$<?=number_format($payment['price'])?></div>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">付款單位</label>
                    <div><?=$payment['paid_retailer']['company']?></div>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">收款單位</label>
                    <div><?=$payment['received_retailer']['company']?></div>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">付款方式</label>
                    <div><?= paymentType($payment['type_id']) ?></div>
                </div>

                <?php if ($payment['receipt']){ ?>
                <div class="form-group">
                    <label class="font-weight-bold">付款憑證</label>
                    <div><img class="img-fluid" src="<?=$payment['receipt']?>" /></div>
                </div>
                <?php } ?>

                <div class="form-group text-center">
                    <input type="submit" name="refused" class="btn btn-danger" value="尚未收款"/>
                    <input type="submit" name="confirmed" class="btn btn-success" value="收款無誤"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/capital/retailer/qualification/edit.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">更新<?= $retailer['company'] ?>經銷拓展資格</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>
                <div class="form-group">
                    <label>類別</label>
                    <input name="type" class="form-control-plaintext" value="<?= $level['type']['title'] ?>"/>
                </div>
                <div class="form-group">
                    <label>代碼</label>
                    <input name="code" class="form-control-plaintext" value="<?= $level['code'] ?>" />
                </div>
                <div class="form-group">
                    <label>名稱</label>
                    <input name="title" class="form-control-plaintext" value="<?= $level['type']['title'] ?>"/>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">經銷拓展資格</label>
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="qualification" id="yesno_1" value="1" required<?php if ($qualification){ echo ' checked';} ?>>
                            <label class="form-check-label" for="yesno_1">是</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="qualification" id="yesno_0" value="0"<?php if (!$qualification){ echo ' checked';} ?>>
                            <label class="form-check-label" for="yesno_0">否</label>
                        </div>
                    </div>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/capital_retailer_qualification/overview/' . $retailer['id'])?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="更新"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/consumer/overview.php
<div class="container">
    <h1 class="mb-4">
        <?= $dealer['company'] ?>歷史銷售紀錄
        <div class="float-right">
            <?php if (!empty($authority['trashed'])){ ?>
                <a href="<?=base_url('/consumer/trashed/') ?>" class="btn btn-warning">取消之消費紀錄</a>
            <?php } ?>
        </div>
    </h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">編號</th>
            <th class="text-center">日期</th>
            <th class="text-center">姓名</th>
            <th class="text-center">電話</th>
            <th class="text-center">總額</th>
            <th class="text-center"></th>
        </tr>
        <?php
        if ($orders) {
            $amount = 0;
            foreach ($orders as $order) {
                $amount += $order['total'];
                ?>
                <tr>
                    <td class="text-center"><?= $order['orderNum'] ?></td>
                    <td class="text-center"><?= date('Y-m-d', strtotime($order['created_at'])) ?></td>
                    <td class="text-center">
                        <?php if (!empty($authority['customer']) && $order['buyer_id']) { ?>
                            <a href="<?= base_url('/customer/consumer/' . $order['buyer_id']) ?>"><?= $order['contact']['name'] ?></a>
                        <?php } ?>
                    </td>
                    <td class="text-center">
                        <?php if ($order['buyer_id']) { ?>
                            <?= $order['contact']['phone'] ?>
                        <?php } ?>
                    </td>
                    <td class="text-right">$<?= number_format($order['total']) ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php if (!empty($authority['detail'])){ ?>
                            <a class="btn btn-info btn-sm" href="<?= base_url('/consumer/detail/' . $order['id']) ?>">
                                <i class="fas fa-search"></i> 明細
                            </a>
                            <?php } ?>

                            <?php
                            if ($order['shipout_retailer_id'] == $dealer['retailer_id']) { ?>
                                <button type="button" class="btn btn-info btn-sm dropdown-toggle dropdown-toggle-split"
                                        data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <span class="sr-only">Toggle Dropdown</span>
                                </button>
                                <div class="dropdown-menu">
                                    <?php if (!empty($authority['edit'])){ ?>
                                        <a class="dropdown-item" href="<?= base_url('/consumer/edit/' . $order['id']) ?>">編輯消費紀錄</a>
                                    <?php } ?>
                                    <?php if (!empty($authority['cancel'])){ ?>
                                    <div class="dropdown-divider"></div>
                                    <a class="dropdown-item" href="#"
                                       data-href="<?= base_url('/consumer/cancel/' . $order['id']) ?>"
                                       data-toggle="modal" data-target="#confirm-delete"><i class="fas fa-trash"></i>
                                        取消消費紀錄</a>
                                    <?php } ?>
                                </div>
                            <?php } ?>
                        </div>
                    </td>
                </tr>
                <?php
            }
            ?>
            <tr>
                <th colspan="4" class="text-right">累計消費金額</th>
                <td class="text-right">
                    $<?= number_format($amount) ?>
                </td>
                <td></td>
            </tr>
            <?php
        } else {
            ?>
            <tr>
                <td colspan="6" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div>

<div class="modal" id="confirm-delete" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-trash"></i> 刪除確認</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>是否確定刪除？</p>
            </div>
            <div class="modal-footer d-flex justify-content-between">
                <button type="button" class="btn" data-dismiss="modal"><i class="fas fa-ban"></i> 取消</button>
                <a href="" class="btn btn-danger btn-confirm"><i class="fas fa-trash"></i> 刪除</a>
            </div>
        </div>
    </div>
</div>

<script>
    $().ready(function () {
        $('#confirm-delete').on('show.bs.modal', function (e) {
            $(this).find('.btn-confirm').attr('href', $(e.relatedTarget).data('href'));
        });
    });
</script><file_sep>/application/views/commission/dealer.php
<div class="container">

    <h1 class="mb-4"><?= $dealer['name'] ?> 輔銷人獎金</h1>
    <h4>輔銷獎金總計 $<?=number_format($total_commission)?></h4>
    <h4><?= $commissionMonth ?>輔銷獎金合計 $<?=number_format($month_total_commission)?></h4>

    <?php
    if ($retailers) {
        foreach ($retailers as $retailer_id => $r) {
            if ($r['commissions']) {
                ?>
                <div class="my-4">
                    <h4 class="mb-2"><?= $r['company'] ?>經銷商(輔銷單位: <?= $r['sales_retailer']['company'] ?>,
                        輔銷人: <?= $r['sales_dealer']['name'] ?>)</h4>
                    <table class="table table-hover table-bordered table-responsive-sm">
                        <tr>
                            <th class="text-center">進貨單編號</th>
                            <th class="text-center">進貨日期</th>
                            <th class="text-center">金額</th>
                            <th class="text-center">獎金</th>
                        </tr>
                        <?php
                        foreach ($r['commissions'] as $commission) {
                            ?>
                            <tr>
                                <td class="text-center"><?= $commission['purchase']['purchaseNum'] ?></td>
                                <td class="text-center"><?= $commission['created_at'] ?></td>
                                <td class="text-right">$<?= number_format($commission['purchase']['total']) ?></td>
                                <td class="text-right">$<?= number_format($commission['total']) ?></td>
                            </tr>
                            <?php
                        }
                        ?>
                        <tr>
                            <th class="text-right" colspan="3">獎金小計</th>
                            <td class="text-right">$<?= number_format($r['subtotal']) ?></td>
                        </tr>
                    </table>
                </div>
                <?php
            }
        }
    }
    ?>

    <div class="text-center my-4">
        <?php if ($prevMonthUrl){ ?>
        <a href="<?=$prevMonthUrl?>" class="btn btn-success mr-2">前一個月</a>
        <?php } ?>
        <?php if ($nextMonthUrl){ ?>
        <a href="<?=$nextMonthUrl?>" class="btn btn-success">後一個月</a>
        <?php } ?>
    </div>
</div><file_sep>/application/controllers/Stock.php
<?php

class Stock extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || !$this->dealer['hasStock']) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_model');
        $this->load->model('stock_model');
        $this->load->model('product_model');

        $this->session->set_userdata('return_page', base_url('/stock/overview'));
    }

    public function overview()
    {
        $retailer_id = $this->dealer['retailer_id'];

        $retailer = $this->retailer_model
            ->get($retailer_id);

        $products = $this->product_model->getUnitProductStocks($retailer_id);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('stock', 'detail')){
            $authority['detail'] = true;
        }

        $data = [
            'retailer' => $retailer,
            'products' => $products,
            'authority' => $authority,
            'title' => '庫存列表',
            'view' => 'stock/overview',
        ];

        $this->_preload($data);
    }

    public function detail($product_id)
    {
        $retailer_id = $this->dealer['retailer_id'];

        $product = $this->product_model
            ->with_pao()
            ->where('pKind', [3,6])
            ->where('pEnable', 'Y')
            ->where('pdId', $product_id)
            ->get();

        if (!$product_id || !$product) {
            show_error('查無經銷單位商品資料！');
        }

        $retailer = $this->retailer_model
            ->get($retailer_id);

        $stocks = $this->stock_model
            ->where('product_id', $product['pdId'])
            ->where('retailer_id', $retailer_id)
            ->where('stock', '>', 0)
            ->order_by('expired_at', 'asc')
            ->get_all();

        $product['stock'] = $this->product_model->calcStock($stocks, $product);

        $data = [
            'retailer' => $retailer,
            'product' => $product,
            'title' => '詳細產品庫存資訊',
            'view' => 'stock/detail',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/controllers/Capital_free_package.php
<?php

class Capital_free_package extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('free_package_item_model');

        $this->session->set_userdata('return_page', base_url('/capital_free_package/overview'));
    }

    public function overview()
    {
        $total_free_packages_count = $this->free_package_item_model
            ->count_rows();

        $free_packages = $this->free_package_item_model
            ->with_product()
            ->order_by('id', 'desc')
            ->paginate(20, $total_free_packages_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_free_package', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('capital_free_package', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'free_packages' => $free_packages,
            'pagination' => $this->free_package_item_model->all_pages,
            'authority' => $authority,
            'title' => '免費包裝列表',
            'view' => 'capital/free_package/overview',
        ];

        $this->_preload($data);
    }

    public function add()
    {
        $this->load->model('product_model');
        $products = $this->product_model->getPackageProducts();

        if ($this->input->post()) {
            $this->form_validation->set_rules('product_id', '包裝產品', 'required|integer|in_list[' . implode(',',array_keys($products)) . ']|callback_check_duplicate');
            
            if ($this->form_validation->run() !== FALSE) {
                $this->free_package_item_model->insert([
                    'product_id' => $this->input->post('product_id'),
                ]);

                redirect(base_url('/capital_free_package/overview/'));
            }
        }

        $data = [
            'products' => $products,
            'title' => '新增免費包裝',
            'view' => 'capital/free_package/add',
        ];

        $this->_preload($data);
    }

    public function check_duplicate($product_id){
        $results = $this->free_package_item_model
            ->where('product_id', $product_id)
            ->get_all();

        if (!$results) {
            return true;
        } else {
            $this->form_validation->set_message('check_duplicate', '此包裝已經建立，請勿重複新增');
            return false;
        }
    }

    public function cancel($id)
    {
        $free_package = $this->free_package_item_model
            ->get($id);

        if (!$id || !$free_package) {
            show_error('查無免費包裝資料');
        }

        $this->free_package_item_model->delete($id);

        redirect(base_url('/capital_free_package/overview/'));
    }
}

?><file_sep>/application/views/customer/old_detail.php
<div class="container">
    <h1 class="mb-4">舊有會員全部匯入資訊</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">會員代號</th>
            <td><?=$customer['customerNum']?></td>
        </tr>
        <tr>
            <th class="text-center">會員名稱</th>
            <td><?=$customer['name']?></td>
        </tr>
        <tr>
            <th class="text-center">有效起始日</th>
            <td><?=$customer['valid_at']?></td>
        </tr>
        <tr>
            <th class="text-center">有效到期日</th>
            <td><?=$customer['expired_at']?></td>
        </tr>
        <tr>
            <th class="text-center">性別</th>
            <td><?=gender($customer['gender'])?></td>
        </tr>
        <tr>
            <th class="text-center">行動電話</th>
            <td><?=$customer['phone']?></td>
        </tr>
        <tr>
            <th class="text-center">地址</th>
            <td><?=$customer['address']?></td>
        </tr>
        <tr>
            <th class="text-center">Email</th>
            <td><?=$customer['email']?></td>
        </tr>
        <tr>
            <th class="text-center">會員卡別</th>
            <td><?=$customer['isVIP'] ? 'VIP' : ''?></td>
        </tr>
        <tr>
            <th class="text-center">消費總金額</th>
            <td>$<?=number_format($customer['amount'])?></td>
        </tr>
        <tr>
            <th class="text-center">購買總次數</th>
            <td><?=$customer['buytimes']?></td>
        </tr>
    </table>
</div><file_sep>/application/config/class_list.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$config = array(
    'capital_dealer' => array(
        'alias' => '系統參數-單位人員管理',
        'method' => array(
            'overview' => '單位人員總覽',
            'add' => '新增單位人員',
            'edit' => '編輯單位人員',
            'cancel' => '刪除單位人員',
        ),
    ),
    'capital_level' => array(
        'alias' => '系統參數-經銷規則管理',
        'method' => array(
            'overview' => '經銷規則總覽',
            'add' => '新增經銷規則',
            'edit' => '編輯經銷規則',
            'cancel' => '刪除經銷規則',
        ),
    ),
    'capital_level_type' => array(
        'alias' => '系統參數-經銷類別管理',
        'method' => array(
            'overview' => '經銷類別總覽',
            'edit' => '編輯經銷類別',
        ),
    ),
    'capital_customer_level' => array(
        'alias' => '系統參數-會員資格管理',
        'method' => array(
            'overview' => '會員資格總覽',
            'edit' => '編輯會員資格',
        ),
    ),
    'capital_privilege' => array(
        'alias' => '系統參數-經銷類別管理',
        'method' => array(
            'overview' => '權限總覽',
            'apps' => '頁面權限總覽',
            'authority' => '動作權限設定',
        ),
    ),
    'capital_relationship_invoice' => array(
        'alias' => '系統參數-發票關係單位管理',
        'method' => array(
            'overview' => '發票關係單位總覽',
            'add' => '新增發票關係單位',
            'edit' => '編輯發票關係單位',
            'cancel' => '刪除發票關係單位',
        ),
    ),
    'capital_relationship_invoice_send' => array(
        'alias' => '系統參數-發票寄送關係單位管理',
        'method' => array(
            'overview' => '發票寄送關係單位總覽',
            'add' => '新增發票寄送關係單位',
            'cancel' => '刪除發票寄送關係單位',
        ),
    ),
    'capital_relationship_shipin' => array(
        'alias' => '系統參數-收貨關係單位管理',
        'method' => array(
            'overview' => '收貨關係單位總覽',
            'add' => '新增收貨關係單位',
            'cancel' => '刪除收貨關係單位',
        ),
    ),
    'capital_relationship_shipout' => array(
        'alias' => '系統參數-出貨關係單位管理',
        'method' => array(
            'overview' => '出貨關係單位總覽',
            'add' => '新增出貨關係單位',
            'edit' => '編輯出貨關係單位',
            'cancel' => '刪除出貨關係單位',
        ),
    ),
    'capital_relationship_visor' => array(
        'alias' => '系統參數-輔銷關係單位管理',
        'method' => array(
            'overview' => '輔銷關係單位總覽',
            'add' => '新增輔銷關係單位',
            'cancel' => '刪除輔銷關係單位',
        ),
    ),
    'capital_retailer' => array(
        'alias' => '系統參數-單位管理',
        'method' => array(
            'overview' => '單位總覽',
            'add' => '新增單位',
            'edit' => '編輯單位',
            'cancel' => '刪除單位',
        ),
    ),
    'capital_retailer_group' => array(
        'alias' => '系統參數-群組管理',
        'method' => array(
            'overview' => '群組總覽',
            'add' => '新增群組',
            'edit' => '編輯群組',
        ),
    ),
    'capital_retailer_role' => array(
        'alias' => '系統參數-單位類型管理',
        'method' => array(
            'overview' => '單位類型總覽',
        ),
    ),
    'capital_retailer_qualification' => array(
        'alias' => '系統參數-經銷拓展資格',
        'method' => array(
            'overview' => '經銷拓展資格總覽',
            'edit' => '編輯經銷拓展資格',
        ),
    ),
    'capital_pao' => array(
        'alias' => '系統參數-商品期限參數',
        'method' => array(
            'overview' => '商品期限參數總覽',
            'add' => '新增商品期限參數',
            'edit' => '編輯商品期限參數',
            'cancel' => '刪除商品期限參數',
        ),
    ),
    'capital_product' => array(
        'alias' => '系統參數-商品管理',
        'method' => array(
            'overview' => '商品總覽',
            'add' => '新增商品',
            'edit' => '編輯商品',
            'cancel' => '刪除商品',
        ),
    ),
    'capital_product_permission' => array(
        'alias' => '系統參數-進貨商品管理',
        'method' => array(
            'overview' => '進貨商品總覽',
            'edit' => '編輯進貨商品',
        ),
    ),
    'capital_product_relationship' => array(
        'alias' => '系統參數-出貨單位產品折扣',
        'method' => array(
            'edit' => '編輯出貨單位產品折扣',
        ),
    ),
    'capital_combo' => array(
        'alias' => '系統參數-商品組合管理',
        'method' => array(
            'overview' => '商品組合總覽',
            'add' => '新增商品組合',
            'edit' => '編輯商品組合',
            'cancel' => '刪除商品組合',
            'check_total' => '檢查商品、數量是否正確',
        ),
    ),
    'capital_free_package' => array(
        'alias' => '系統參數-免費包裝管理',
        'method' => array(
            'overview' => '免費包裝總覽',
            'add' => '新增免費包裝',
            'cancel' => '刪除免費包裝',
            'check_duplicate' => '檢查是否有重複新增免費包裝商品',
        ),
    ),
    'capital_promote' => array(
        'alias' => '系統參數-優惠活動管理',
        'method' => array(
            'overview' => '優惠活動總覽',
            'add' => '新增優惠活動',
            'edit' => '編輯優惠活動',
            'cancel' => '刪除優惠活動',
        ),
    ),
    'capital_promote_method' => array(
        'alias' => '系統參數-優惠方式管理',
        'method' => array(
            'overview' => '優惠方式總覽',
            'add' => '新增優惠方式',
            'edit' => '編輯優惠方式',
            'cancel' => '刪除優惠方式',
        ),
    ),
    'capital_option' => array(
        'alias' => '系統參數-其他',
        'method' => array(
            'customer' => '編輯消費者參數',
        ),
    ),
    'capital_stock' => array(
        'alias' => '單位庫存',
        'method' => array(
            'overview' => '單位庫存總覽',
            'detail' => '詳細產品庫存資訊',
        ),
    ),
    'stock' => array(
        'alias' => '該單位庫存',
        'method' => array(
            'overview' => '該單位庫存總覽',
            'detail' => '詳細產品庫存資訊',
        ),
    ),
    'stock_counting' => array(
        'alias' => '盤點作業',
        'method' => array(
            'index' => '盤點作業首頁選單',
            'overview' => '盤點歷史紀錄列表',
            'detail' => '盤盈虧報表',
            'set_print' => '盤點清冊下載',
            'process_print' => '盤點清冊列印',
            'add' => '盤盈虧報表新增',
            'edit' => '盤盈虧報表編輯',
        ),
    ),
    'guest' => array(
        'alias' => '經銷商首次訂購',
        'method' => array(
            'level' => '經銷商身份類別選擇',
            'cart' => '經銷商訂貨表單',
            'check_total' => '檢查商品、數量、庫存、門檻是否正確',
            'adminCheck' => '總監登入確認',
            'check_authentic' => '總監登入帳號驗證',
            'info' => '經銷商基本資料表單',
        ),
    ),
    'purchase' => array(
        'alias' => '進貨單管理',
        'method' => array(
            'overview' => '進貨單列表',
            'detail' => '進貨單詳細資料',
            'detail2' => '進貨單詳細資料(無金額)',
            'add' => '新增進貨單',
            'add2' => '新增進貨單(無金額)',
            'check_total' => '檢查商品、數量、庫存、門檻是否正確',
            'edit' => '編輯進貨單',
            'cancel' => '取消進貨單',
        ),
    ),
    'transfer' => array(
        'alias' => '出貨單管理',
        'method' => array(
            'overview' => '出貨單列表',
            'transfer' => '向上轉單動作',
            'detail' => '出貨單詳細資料',
            'detail2' => '出貨單詳細資料(無金額)',
            'confirm' => '確認出貨單動作',
        ),
    ),
    'payment' => array(
        'alias' => '付款管理',
        'method' => array(
            'overview' => '付款紀錄列表',
            'add' => '新增付款紀錄',
            'confirms' => '待確認收款列表',
            'confirm' => '確認付款動作',
            'cancel' => '取消付款紀錄',
            'purchase' => '進貨單位付款紀錄轉址',
        ),
    ),
    'shipment' => array(
        'alias' => '銷貨紀錄管理',
        'method' => array(
            'overview' => '銷貨紀錄列表',
            'detail' => '銷貨紀錄列表',
            'add' => '新增銷貨紀錄',
            'check_shipping_qty' => '檢查新增銷貨商品、數量、庫存是否正確',
            'confirm' => '確認銷貨',
            'check_qty' => '檢查確認銷貨商品、數量是否正確',
            'cancel' => '取消銷貨紀錄',
            'revise_edit' => '編輯銷貨異動',
            'confirm_revise' => '確認銷貨異動',
            'return_add' => '新增銷貨退回',
            'check_return_qty' => '檢查新增銷貨退回商品、數量是否正確',
            'confirm_return' => '確認銷貨退回',
            'allowance_add' => '新增銷貨折讓',
        ),
    ),
    'commission' => array(
        'alias' => '獎金',
        'method' => array(
            'dealers' => '輔銷人名單',
            'dealer' => '輔銷人獎金',
        ),
    ),
    'confirm' => array(
        'alias' => '確認紀錄',
        'method' => array(
            'overview' => '確認紀錄列表',
        ),
    ),
    'income' => array(
        'alias' => '財務管理',
        'method' => array(
            'overview' => '營業資訊',
            'product' => '商品業績',
        ),
    ),
    'customer' => array(
        'alias' => '消費者管理',
        'method' => array(
            'overview' => '消費者搜尋',
            'edit' => '編輯消費者',
            'consumer' => '該消費者歷史消費記錄',
            'upgrade' => '符合飄雪白卡資格升級動作',
            'old' => '未轉換舊有會員資訊',
            'old_detail' => '舊有會員全部匯入資訊',
            'conv_old' => '舊有會員轉換表單',
            'active_old' => '會員資料區',
            'import' => '匯入舊有會員資訊',
            'export' => '匯出會員資訊',
        ),
    ),
    'consumer' => array(
        'alias' => '消費者消費管理',
        'method' => array(
            'index' => '消費紀錄選單',
            'overview' => '銷售單位歷史銷售',
            'detail' => '消費者消費明細',
            'add' => '新增消費紀錄',
            'check_qty' => '檢查商品、數量、庫存是否正確',
            'check_promote' => '檢查優惠活動選擇是否正確',
            'check_coupon' => '檢查核發優惠券是否重複',
            'edit' => '編輯消費紀錄',
            'cancel' => '刪除消費紀錄',
            'old' => '舊有會員轉換',
            'check_oldphone' => '檢查舊有會員是否已轉換',
            'trashed' => '取消之消費紀錄',
            'recover' => '恢復取消的消費紀錄',
            'payAtShipped' => '貨到付款管理',
            'shipping' => '貨到付款確認寄出',
            'paying' => '貨到付款收款作業',
            'reject' => '貨到付款客戶拒收',
            'orderReturn' => '貨到付款退貨作業',
            'transfer' => 'A店買B店取貨之紀錄',
            'transfer_record' => 'A店買B店取貨開立取貨單',
            'transfer_delivery' => 'A店買B店取貨確認取貨',
        ),
    ),
    'coupon' => array(
        'alias' => '折價券管理',
        'method' => array(
            'overview' => '折價券核發紀錄',
            'edit' => '貴賓優惠券序號登錄',
        ),
    ),
    'recommend' => array(
        'alias' => '行銷作業管理',
        'method' => array(
            'overview' => '行銷作業區',
            'temp' => '暫存作業區',
            'add' => '來賓推薦作業',
            'print_recommend' => '來賓推薦作業列印',
            'edit' => '修改行銷作業',
        ),
    ),
    'recommend_template' => array(
        'alias' => '推薦函管理',
        'method' => array(
            'index' => '推薦函之增修',
            'confirm' => '檢視或修改定案之推薦函',
            'confirm_edit' => '修改定案之推薦函',
            'inside' => '檢視或修改內部撰寫之推薦函',
            'inside_add' => '新增內部撰寫之推薦函',
            'inside_edit' => '修改定案之推薦函',
            'outside' => '檢視或修改外部撰寫之推薦函',
            'outside_add' => '新增外部撰寫之推薦函',
            'outside_edit' => '修改外部撰寫之推薦函',
            'confirming' => '內部、外部撰寫之推薦函定案動作',
        ),
    ),
    'dealer' => array(
        'alias' => '個人資料管理',
        'method' => array(
            'edit' => '單位資料修改',
            'profile' => '個人資料修改',
            'password' => '<PASSWORD>',
            'check_password' => '<PASSWORD>',
        ),
    ),
    'retailer' => array(
        'alias' => '單位人員管理',
        'method' => array(
            'overview' => '單位人員列表',
            'add' => '新增人員帳號',
            'edit' => '編輯人員帳號',
            'cancel' => '刪除人員帳號',
        ),
    ),
    'supervisor' => array(
        'alias' => '經銷商列表',
        'method' => array(
            'overview' => '經銷商列表',
            'info' => '經銷單位基本資料',
            'purchase' => '經銷商進貨明細',
            'detail' => '進貨單詳細資料',
        ),
    ),
);
<file_sep>/application/controllers/Retailer.php
<?php

class Retailer extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged())) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_model');
        $this->load->model('dealer_model');

        $this->session->set_userdata('return_page', base_url('/retailer/overview'));
    }

    public function overview()
    {
        $total_dealers_count = $this->dealer_model
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->where('isLocked', 0)
            ->count_rows();

        $dealers = $this->dealer_model
            ->with_group()
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->where('isLocked', 0)
            ->order_by('id', 'desc')
            ->paginate(20, $total_dealers_count);

        $this->load->helper('data_format');

        //權限設定
        $authority = array();
        if ($this->authentic->authority('retailer', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('retailer', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('retailer', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'dealers' => $dealers,
            'pagination' => $this->dealer_model->all_pages,
            'authority' => $authority,
            'title' => $this->dealer['company'] . '人事管理',
            'view' => 'retailer/overview',
        ];

        $this->_preload($data);
    }

    public function add()
    {
        $this->load->model('retailer_group_model');
        $groups = $this->retailer_group_model->getGroupSelect($this->dealer['retailer_role_id'], (empty($this->dealer['level']['type_id']) ? null : $this->dealer['level']['type_id']));

        if ($this->input->post()) {
            $this->form_validation->set_rules('retailer_group_id', '群組', 'required|integer|in_list[' . implode(',',array_keys($groups)) . ']');
            $this->form_validation->set_rules('account', '帳號', 'required|alpha_numeric|min_length[3]|max_length[10]|valid_dealer_account');
            $this->form_validation->set_rules('password', '密碼', 'required|min_length[6]');
            $this->form_validation->set_rules('password_confirm', '確認密碼', 'required|min_length[6]|matches[password]');
            $this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
            $this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');

            if ($this->form_validation->run() !== FALSE) {
                $insert_data = [
                    'retailer_id' => $this->dealer['retailer_id'],
                    'retailer_group_id' => $this->input->post('retailer_group_id'),
                    'account' => $this->input->post('account'),
                    'password' => $<PASSWORD>->authentic->_mix($this->input->post('password')),
                    'name' => $this->input->post('name'),
                    'gender' => $this->input->post('gender'),
                ];

                $this->dealer_model->insert($insert_data);

                redirect(base_url('/retailer/overview'));
            }
        }

        $data = [
            'groups' => $groups,
            'title' => '新增人員帳號',
            'view' => 'retailer/add',
        ];

        $this->_preload($data);
    }

    public function edit($dealer_id)
    {
        $this->load->model('retailer_group_model');
        $groups = $this->retailer_group_model->getGroupSelect($this->dealer['retailer_role_id'], (empty($this->dealer['level']['type_id']) ? null : $this->dealer['level']['type_id']));

        $ddealer = $this->dealer_model
            ->with_retailer()
            ->get($dealer_id);

        if (!$dealer_id || !$ddealer) {
            show_error('查無人員資料');
        }

        if ($ddealer['isLocked']){
            show_error('此人員不能刪除');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('retailer_group_id', '群組', 'required|integer|in_list[' . implode(',',array_keys($groups)) . ']');
            $this->form_validation->set_rules('password', '密碼', '<PASSWORD>]');
            $this->form_validation->set_rules('password_confirm', '<PASSWORD>', '<PASSWORD>[6]|matches[password]');
            $this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
            $this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');

            if ($this->form_validation->run() !== FALSE) {
                $update_data = [
                    'retailer_group_id' => $this->input->post('retailer_group_id'),
                    'name' => $this->input->post('name'),
                    'gender' => $this->input->post('gender'),
                ];

                if ($this->input->post('password')){
                    $update_data['password'] = $this->authentic->_mix($this->input->post('password'));
                }
                $this->dealer_model->update($update_data, ['id' => $dealer_id]);

                redirect(base_url('/retailer/overview'));
            }
        }

        $data = [
            'groups' => $groups,
            'ddealer' => $ddealer,
            'title' => '編輯人員帳號',
            'view' => 'retailer/edit',
        ];

        $this->_preload($data);
    }

    public function cancel($dealer_id)
    {
        $dealer = $this->dealer_model
            ->get($dealer_id);

        if (!$dealer_id || !$dealer) {
            show_error('查無經銷人員資料');
        }

        if ($dealer_id == $this->dealer['id']){
            show_error('不能刪除自己');
        }

        if ($dealer['isLocked']){
            show_error('此經銷人員不能刪除');
        }

        $retailer = $this->retailer_model
            ->get($dealer['retailer_id']);

        if ($retailer && $retailer['contact_dealer_id'] == $dealer_id){
            show_error('預設人員不能刪除');
        }

        $this->dealer_model->delete($dealer_id);

        redirect(base_url('/retailer/overview'));
    }
}

?><file_sep>/application/controllers/Index.php
<?php

class Index extends MY_Controller
{
    protected $title, $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!$this->dealer = $this->authentic->isLogged()) {
            redirect(base_url('/auth/login'));
        }
    }

    public function index()
    {
        $data = [
            'title' => '首頁',
            'view' => 'welcome',
        ];
//        print_r($this->dealer);

        $this->_preload($data);
    }
}
?><file_sep>/application/controllers/Capital_retailer_group.php
<?php

class Capital_retailer_group extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_role_model');
        $this->load->model('retailer_level_type_model');
        $this->load->model('retailer_group_model');

        $this->session->set_userdata('return_page', base_url('/capital_retailer_group/overview'));
    }

    public function overview($id)
    {
        $tmp = explode('_', $id);
        $role = [];
        if (!empty($tmp[0])){
            $retailer_role_id = (int)$tmp[0];
            $retailer_level_type_id = empty($tmp[1]) ? null : (int)$tmp[1];

            $role = $this->retailer_role_model
                ->with_level_types()
                ->get($retailer_role_id);

            if ($retailer_role_id && $role){
                if ($role['level_types'] || $retailer_level_type_id){
                    $level_type = $this->retailer_level_type_model
                        ->where('retailer_role_id', $retailer_role_id)
                        ->get($retailer_level_type_id);
                    if (!$retailer_level_type_id || !$level_type){
                        show_error('查無單位類型資料');
                    } else {
                        $role['title'] = $level_type['title'];
                    }
                }
            }
        }

        if (!$role){
            show_error('查無單位類型資料');
        }

        if ($retailer_level_type_id){
            $this->retailer_group_model->where('retailer_level_type_id', $retailer_level_type_id);
        }

        $groups = $this->retailer_group_model
            ->where('retailer_role_id', $retailer_role_id)
            ->get_all();

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_retailer_group', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('capital_retailer_group', 'edit')){
            $authority['edit'] = true;
        }

        $data = [
            'id' => $id,
            'role' => $role,
            'groups' => $groups,
            'authority' => $authority,
            'title' => '群組總覽',
            'view' => 'capital/retailer/group/overview',
        ];

        $this->_preload($data);
    }

    public function add($id)
    {
        $tmp = explode('_', $id);
        $role = [];
        if (!empty($tmp[0])){
            $retailer_role_id = (int)$tmp[0];
            $retailer_level_type_id = empty($tmp[1]) ? null : (int)$tmp[1];

            $role = $this->retailer_role_model
                ->with_level_types()
                ->get($retailer_role_id);

            if ($retailer_role_id && $role){
                if ($role['level_types'] || $retailer_level_type_id){
                    $level_type = $this->retailer_level_type_model
                        ->where('retailer_role_id', $retailer_role_id)
                        ->get($retailer_level_type_id);
                    if (!$retailer_level_type_id || !$level_type){
                        show_error('查無單位類型資料');
                    } else {
                        $role['title'] = $level_type['title'];
                    }
                }
            }
        }

        if (!$role){
            show_error('查無單位類型資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('title', '名稱', 'required|max_length[10]');

            if ($this->form_validation->run() !== FALSE) {
                $insert_data = [
                    'title' => $this->input->post('title'),
                    'retailer_role_id' => $retailer_role_id,
                    'retailer_level_type_id' => $retailer_level_type_id,
                ];
                $this->retailer_group_model->insert($insert_data);

                redirect(base_url('/capital_retailer_group/overview/' . $id));
            }
        }

        $data = [
            'id' => $id,
            'role' => $role,
            'title' => '新增群組',
            'view' => 'capital/retailer/group/add',
        ];

        $this->_preload($data);
    }

    public function edit($group_id)
    {
        $group = $this->retailer_group_model
            ->get($group_id);

        if (!$group_id || !$group) {
            show_error('查無群組資料');
        }

        if ($group['retailer_role_id'] == 5) {
            $overview_url = base_url('/capital_retailer_group/overview/' . $group['retailer_role_id'] . '_' . $group['retailer_level_type_id']);
        } else {
            $overview_url = base_url('/capital_retailer_group/overview/' . $group['retailer_role_id']);
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('title', '名稱', 'required|max_length[10]');

            if ($this->form_validation->run() !== FALSE) {
                $update_data = [
                    'title' => $this->input->post('title'),
                ];
                $this->retailer_group_model->update($update_data, ['id' => $group_id]);

                redirect($overview_url);
            }
        }

        $data = [
            'group' => $group,
            'overview_url' => $overview_url,
            'title' => '編輯群組',
            'view' => 'capital/retailer/group/edit',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/models/Purchase_item_model.php
<?php

class Purchase_item_model extends MY_Model
{
    public $table = 'olive_purchase_items';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
        $this->has_one['product'] = array('foreign_model' => 'Product_model', 'foreign_table' => 'product', 'foreign_key' => 'pdId', 'local_key' => 'product_id');
    }

    public function getPurchaseItemOfId($purchase_id, $product_id)
    {
        return $this
            ->with_purchase()
            ->where('purchase_id', $purchase_id)
            ->where('product_id', $product_id)
            ->get();
    }
}

?>
<file_sep>/application/models/Product_kind_model.php
<?php
class Product_kind_model extends MY_Model{
    public $table = 'product_kind';
    public $primary_key = 'ctId';

    function __construct(){
        parent::__construct();

        $this->timestamps = false;
        $this->return_as = 'array';
    }

    public function getKindSelect()
    {
        $_kinds = $this
            ->where('ctId', [3,6])
            ->get_all();
        $kinds = [];
        foreach ($_kinds as $kind){
            $kinds[$kind['ctId']] = $kind['ctName'];
        }
        return $kinds;
    }
}
?>
<file_sep>/application/views/shipment/revise_edit.php
<div class="container">
    <h1 class="mb-4">編輯銷貨異動</h1>

    <form method="post" id="shipmentForm" enctype="multipart/form-data">
        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th>項次</th>
                <th>貨品編號 / 貨品名稱</th>
                <th>訂購數量</th>
                <th>到期日</th>
                <th>出貨數量</th>
                <th>收貨數量</th>
                <th>備註</th>
                <th>照片</th>
            </tr>
            <?php
            if ($shipment['items']) {
                $i = 1;
                foreach ($shipment['items'] as $item) {
                    if (empty($products[$item['product_id']])){
                        continue;
                    }
                    $stock_row = count($products[$item['product_id']]);
                    ?>
                    <tr>
                        <td class="text-center" rowspan="<?=$stock_row?>"><?= $i ?></td>
                        <td rowspan="<?=$stock_row?>"><?= $item['product']['p_num'] ?> <br /><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
                        <td class="text-right" rowspan="<?=$stock_row?>"><?= number_format($item['qty']) ?></td>
                        <?php
                        foreach ($products[$item['product_id']] as $key => $stock){
                            if ($key > 0){
                                echo '</tr><tr>';
                            }
                        ?>
                        <td><?=$stock['expired_at'] ? $stock['expired_at'] : '未標示'?></td>
                        <td class="text-right"><?= $stock['qty'] ?></td>
                        <td class="text-center">
                            <input type="number" min="0" data-stock="<?=$stock['qty']?>" class="input_qty form-control text-right" name="items[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>][qty]" value="<?= empty($stock['revise']) ? $stock['qty'] : $stock['revise']['qty'] ?>" style="width: 120px;" />
                        </td>
                        <td class="text-center">
                            <textarea disabled name="items[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>][memo]" class="text_qty_memo form-control" style="min-width: 120px;"><?= empty($stock['revise']) ? '' : $stock['revise']['memo'] ?></textarea>
                        </td>
                        <td>
                            <input type="hidden" name="items[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>][memo_file]" value="<?= empty($stock['revise']) ? '' : $stock['revise']['memo_file'] ?>" />
                            <input disabled type="file" class="input_qty_file form-control-file" name="memo_pictures[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>]" style="min-width: 120px;" />
                            <?php if (!empty($stock['revise']['memo_file'])){ ?>
                                <br /><a href="<?=$stock['revise']['memo_file']?>" target="_blank" class="btn btn-info">附件</a>
                            <?php } ?>
                        </td>
                        <?php } ?>
                    </tr>
                    <?php
                    $i++;
                }
            }
            ?>
        </table>

        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group text-center">
            <a href="<?=base_url('/purchase/detail/' . $shipment['ship_id'])?>" class="btn btn-secondary">取消</a>
            <input type="submit" name="confirmed" class="btn btn-success" value="更新銷貨異動"/>
        </div>
    </form>
</div>

<script>
    $().ready(function () {
        $('.input_qty').change(function(){
            var shipin_qty = parseInt($(this).val()) || 0;
            var stock_qty = parseInt($(this).data('stock')) || 0;
            if (shipin_qty != stock_qty){
                $(this).parents('tr').find('.text_qty_memo').prop('disabled', false);
                $(this).parents('tr').find('.input_qty_file').prop('disabled', false);
            } else {
                $(this).parents('tr').find('.text_qty_memo').prop('disabled', true);
                $(this).parents('tr').find('.input_qty_file').prop('disabled', true);
            }
        });

        $('.input_qty').trigger('change');

        $("#shipmentForm").submit(function (e) {
            $.each($('input.input_qty'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });

            $.each($('textarea.text_qty_memo'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });

            $.each($('input.input_qty_file'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });
        });
    });
</script><file_sep>/application/controllers/Capital_relationship_shipout.php
<?php

class Capital_relationship_shipout extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_model');
        $this->load->model('retailer_relationship_model');

        $this->session->set_userdata('return_page', base_url('/capital_retailer/overview'));
    }

    public function overview($retailer_id)
    {
        $retailer = $this->retailer_model
            ->get($retailer_id);

        if (!$retailer_id || !$retailer) {
            show_error('查無單位資料！');
        }

        $total_relationships_count = $this->retailer_relationship_model
            ->with_relation()
            ->where('relation_type', 'shipout')
            ->where('retailer_id', $retailer_id)
            ->count_rows();

        $relationships = $this->retailer_relationship_model
            ->with_relation()
            ->where('relation_type', 'shipout')
            ->where('retailer_id', $retailer_id)
            ->order_by('relation_retailer_id')
            ->paginate(20, $total_relationships_count);

        $this->load->helper('data_format');

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_relationship_shipout', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('capital_relationship_shipout', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('capital_product_relationship', 'edit')){
            $authority['product'] = true;
        }
        if ($this->authentic->authority('capital_relationship_shipout', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'retailer' => $retailer,
            'relationships' => $relationships,
            'pagination' => $this->retailer_relationship_model->all_pages,
            'authority' => $authority,
            'title' => $retailer['company'] . '出貨關係單位',
            'view' => 'capital/relationship/shipout/overview',
        ];

        $this->_preload($data);
    }

    public function add($retailer_id)
    {
        $retailer = $this->retailer_model
            ->get($retailer_id);

        if (!$retailer_id || !$retailer) {
            show_error('查無單位資料！');
        }

        $retailer_selects = $this->retailer_model->getRetailerSelect();

        if ($this->input->post()) {
            $this->form_validation->set_rules('relation_retailer_id', '出貨單位', 'required|integer|in_list[' . implode(',',array_keys($retailer_selects)) . ']');
            $this->form_validation->set_rules('discount', '折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');

            if ($this->form_validation->run() !== FALSE) {
                $this->retailer_relationship_model->insert([
                    'relation_type' => 'shipout',
                    'retailer_id' => $retailer_id,
                    'relation_retailer_id' => $this->input->post('relation_retailer_id'),
                    'discount' => $this->input->post('discount'),
                ]);

                redirect(base_url('/capital_relationship_shipout/overview/' . $retailer_id));
            }
        }

        $this->load->helper('form');

        $data = [
            'retailer' => $retailer,
            'retailer_selects' => $retailer_selects,
            'title' => '新增出貨關係單位',
            'view' => 'capital/relationship/shipout/add',
        ];

        $this->_preload($data);
    }

    public function edit($relationship_id)
    {
        $relationship = $this->retailer_relationship_model
            ->with_retailer()
            ->with_relation()
            ->get($relationship_id);

        if (!$relationship_id || !$relationship) {
            show_error('查無出貨關係單位資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('discount', '折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');

            if ($this->form_validation->run() !== FALSE) {
                $this->retailer_relationship_model->update([
                    'discount' => $this->input->post('discount'),
                ], ['id' => $relationship_id]);

                redirect(base_url('/capital_relationship_shipout/overview/' . $relationship['retailer_id']));
            }
        }

        $data = [
            'relationship' => $relationship,
            'title' => '編輯出貨關係單位',
            'view' => 'capital/relationship/shipout/edit',
        ];

        $this->_preload($data);
    }

    public function cancel($relationship_id)
    {
        $relationship = $this->retailer_relationship_model
            ->get($relationship_id);

        if (!$relationship_id || !$relationship) {
            show_error('查無出貨關係單位資料');
        }

        $this->retailer_relationship_model->delete($relationship_id);

        redirect(base_url('/capital_relationship_shipout/overview/' . $relationship['retailer_id']));
    }
}

?><file_sep>/application/views/capital/option/customer.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">編輯消費者參數</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>員工每季消費上限</label>.
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text">$</span>
                        </div>
                        <input type="number" name="customer_staff_max_amount" class="form-control text-right" value="<?= set_value('customer_staff_max_amount', isset($options['customer_staff_max_amount']) ? $options['customer_staff_max_amount'] : '') ?>" required min="0" />
                    </div>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <input type="submit" class="btn btn-success" value="更新"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/migrations/064_update_consumer_send_address.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_consumer_send_address extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_column('olive_order_contacts', [
            'altAddress' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true,
                'after' => 'address',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_order_contacts', 'altAddress');
    }
}<file_sep>/application/models/Retailer_relationship_model.php
<?php

class Retailer_relationship_model extends MY_Model
{
    public $table = 'olive_retailer_relationships';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
        $this->has_one['relation'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'relation_retailer_id');
        $this->has_one['alter'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'alter_retailer_id');
    }
}

?>
<file_sep>/application/controllers/Auth.php
<?php

class Auth extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();

        $except_method = ['loginCheck', 'validate_credentialsAjax', 'logout'];
        if ($this->authentic->isLogged() && !in_array($this->router->fetch_method(), $except_method)) {
            redirect(base_url('/'));
        }
    }

    public function register()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('account', '輔銷人之經銷商代號', 'trim|required');
            $this->form_validation->set_rules('password', '密碼', 'trim|required|callback_check_authentic');

            if ($this->form_validation->run() !== FALSE) {
                $this->session->set_userdata('guest', [
                    'admin_check_discount' => false,
                    'sales_retailer' => [], //輔銷單位
                    'sales_dealer' => $this->authentic->isLogged(), //輔銷人
                    'retailer' => [
                        'account' => '',
                        'company' => '',
                        'identity' => '',
                        'contact' => '',
                        'gender' => 1,
                        'phone' => '',
                        'altPhone' => '',
                        'address' => '',
                    ],
                    'purchase' => [
                        'cart' => [],
                        'total' => 0,
                        'memo' => '',
                    ],
                ]);

                redirect(base_url('/guest/level'), 'refresh');
            }
        }

        $data = [
            'title' => '輔銷人登入',
            'view' => 'auth/register',
        ];
        $this->_preload($data, 'login');
    }

    public function login()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('account', '代號', 'trim|required');
            $this->form_validation->set_rules('password', '密碼', 'trim|required|callback_check_authentic');

            if ($this->form_validation->run() !== FALSE) {
                $return_page = $this->session->userdata('return_page');
                if ($return_page) {
                    $this->session->unset_userdata('return_page');
                    redirect(base_url($return_page), 'refresh');
                } else {
                    redirect(base_url('/'), 'refresh');
                }
            }
        }
        $data = [
            'title' => '登入',
            'view' => 'auth/login',
        ];
        $this->_preload($data, 'login');
    }

    public function check_authentic($password)
    {
        if ($this->authentic->authenticate($this->input->post('account'), $password)) {
            return true;
        } else {
            $this->form_validation->set_message('check_authentic','您輸入的帳號密碼錯誤，請重新確認');
            return false;
        }
    }

    public function logout()
    {
        $this->authentic->logout();
        $this->session->set_userdata(array('msg' => '您已經成功登出'));

        redirect('/');
    }

    //驗證登入狀態
    public function loginCheck()
    {
        if ($this->authentic->isLogged()){
            echo 'ok';
        } else {
            echo 'error';
        }
    }

    public function validate_credentialsAjax()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('account', '代號', 'trim|required');
            $this->form_validation->set_rules('password', '密碼', 'trim|required|callback_<PASSWORD>');

            if ($this->form_validation->run() == FALSE) {
                $error_data = array(
                    'error' => validation_errors(),
                );
                echo json_encode($error_data);
            } else {
                $success_data = array(
                    'dealer' => $this->authentic->isLogged(),
                );
                echo json_encode($success_data);
            }
        }
        $error_data = array(
            'error' => '非法登入',
        );
        echo json_encode($error_data);
    }
}
?><file_sep>/application/models/Recommend_model.php
<?php

class Recommend_model extends MY_Model
{
    public $table = 'olive_recommends';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['template'] = array('foreign_model' => 'Recommend_template_model', 'foreign_table' => 'olive_recommend_templates', 'foreign_key' => 'id', 'local_key' => 'recommend_template_id');
    }
}

?>
<file_sep>/application/controllers/Consumer.php
<?php

class Consumer extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!$this->dealer = $this->authentic->isLogged()) {
            redirect(base_url('/auth/login'));
        }

        $this->load->model('customer_model');
        $this->load->model('old_customer_model');
        $this->load->model('order_model');
        $this->load->model('shipment_model');
        $this->load->model('shipment_item_model');
        $this->load->model('shipment_expiration_model');
        $this->load->model('payment_model');
        $this->load->model('order_return_model');
        $this->load->model('order_return_item_model');
        $this->load->model('order_transfer_model');
        $this->load->model('stock_model');
        $this->load->library('customer_lib');
        $this->load->library('stock_lib');
        $this->load->helper('data_format');

        $this->session->set_userdata('return_page', base_url('/consumer/overview'));

        $this->payment_type = [
            1 => '現金付款取貨',
            3 => '信用卡付款取貨',
            4 => '貨到付款',
            5 => '其他門市取貨',
        ];
    }

    public function index()
    {
        //權限設定
        $authority = array();
        if ($this->authentic->authority('customer', 'overview')) {
            $authority['customer'] = true;
        }
        if ($this->authentic->authority('consumer', 'overview')) {
            $authority['consumer'] = true;
        }
        if ($this->authentic->authority('coupon', 'overview')) {
            $authority['coupon'] = true;
        }

        $data = [
            'authority' => $authority,
            'title' => '消費者歷史消費紀錄',
            'view' => 'consumer/index',
        ];

        $this->_preload($data);
    }

    public function overview()
    {
        $total_orders_count = $this->order_model
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->count_rows();

        $orders = $this->order_model
            ->with_contact()
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->order_by($this->order_model->get_table_name() . '.id', 'desc')
            ->paginate(20, $total_orders_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('customer', 'consumer')) {
            $authority['customer'] = true;
        }
        if ($this->authentic->authority('consumer', 'detail')) {
            $authority['detail'] = true;
        }
        if ($this->authentic->authority('consumer', 'trashed')) {
            $authority['trashed'] = true;
        }
        if ($this->authentic->authority('consumer', 'edit')) {
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('consumer', 'cancel')) {
            $authority['cancel'] = true;
        }

        $data = [
            'orders' => $orders,
            'pagination' => $this->order_model->all_pages,
            'authority' => $authority,
            'title' => '銷售單位歷史銷售',
            'view' => 'consumer/overview',
        ];

        $this->_preload($data);
    }

    public function trashed()
    {
        $total_orders_count = $this->order_model
            ->only_trashed()
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->count_rows();

        $orders = $this->order_model
            ->only_trashed()
            ->with_contact()
            ->with_dealer(['with' => ['relation' => 'trashed']])
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->order_by($this->order_model->get_table_name() . '.id', 'desc')
            ->paginate(20, $total_orders_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('consumer', 'detail')) {
            $authority['detail'] = true;
        }
        if ($this->authentic->authority('consumer', 'recover')) {
            $authority['recover'] = true;
        }

        $data = [
            'orders' => $orders,
            'pagination' => $this->order_model->all_pages,
            'authority' => $authority,
            'title' => '取消之消費紀錄',
            'view' => 'consumer/trashed',
        ];

        $this->_preload($data);
    }

    public function detail($order_id)
    {
        $order = $this->order_model
            ->with_trashed()
            ->where('buyer_type', 'customer')
            ->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
            ->with_customer(['with' => ['relation' => 'level']])
            ->with_shipout_retailer()
            ->with_dealer(['with' => ['relation' => 'trashed']])
            ->with_contact()
            ->with_recipient()
            ->get($order_id);

        if (!$order_id || !$order) {
            show_error('查無消費紀錄');
        }

        $this->load->helper('data_format');

        $shipment = $this->shipment_model
            ->with_expirations(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
            ->where('ship_type', 'consumer')
            ->where('ship_id', $order_id)
            ->where('isConfirmed', 1)
            ->get();

        $data = [
            'order' => $order,
            'shipment' => $shipment,
            'title' => '消費者消費明細',
            'view' => 'consumer/detail',
        ];

        $this->_preload($data);
    }

    public function old()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('name', '姓名', 'max_length[20]');
            $this->form_validation->set_rules('phone', '電話', 'is_natural|max_length[20]|callback_check_oldCustomer[' . $this->input->post('name') . ']');
            if ($this->form_validation->run() !== FALSE) {
                $this->old_customer_model->group_start();
                if (!empty($this->input->post('phone'))) {
                    $this->old_customer_model->where('phone', $this->input->post('phone'), null, true);
                }
                if (!empty($this->input->post('name'))) {
                    $this->old_customer_model->where('name', $this->input->post('name'), null, true);
                }
                $customer = $this->old_customer_model->group_end()->where('isActive', 0)->get();

                if (!empty($_POST['submit_buy'])) {
                    redirect(base_url('/consumer/add/old_' . $customer['id']));
                } else {
                    redirect(base_url('/customer/conv_old/' . $customer['id']));
                }
            }
        }

        $data = [
            'title' => '舊有會員轉換',
            'view' => 'consumer/old',
        ];

        $this->_preload($data);
    }

    public function check_oldCustomer($phone, $name)
    {
        $error = '';
        if (empty($phone) && empty($name)) {
            $error = '查無舊有會員';
        } else {
            $this->old_customer_model->group_start();
            if (!empty($phone)) {
                $this->old_customer_model->where('phone', $phone, null, true);
            }
            if (!empty($name)) {
                $this->old_customer_model->where('name', $name, null, true);
            }
            $customer = $this->old_customer_model->group_end()->get();

            if (!$customer) {
                $error = '查無舊有會員';
            } else {
                if ($customer['isActive']) {
                    $error = '此舊有會員已轉換';
                }
            }
        }

        if (!$error) {
            return true;
        } else {
            $this->form_validation->set_message('check_oldCustomer', $error);
            return false;
        }
    }

    public function add($customer_id = '')
    {
        $this->load->model('promote_model');
        $this->load->model('promote_use_model');
        $this->load->model('product_model');
        $this->load->model('combo_model');
        $this->load->model('free_package_item_model');
        $this->load->model('option_model');

        $customer = [];
        $discount_type = 'P';
        $discount = $member_discount = 100;
        $old_customer = false;

        $option = $this->option_model
            ->where('name', 'customer_staff_max_amount')
            ->get();
        $staff_max_amount = !empty($option['value']) ? (int)$option['value'] : null;

        if ($customer_id) {
            $tmp = explode('_', $customer_id);
            if (!empty($tmp[0]) && $tmp[0] == 'old') {
                $old_customer = true;
                if (!empty($tmp[1])) {
                    $old_customer_id = $tmp[1];
                    $old_customer = $this->old_customer_model
                        ->with_customer()
                        ->get($old_customer_id);
                    if (!$old_customer) {
                        show_error('查無舊有會員');
                    } else {
                        if ($old_customer['isActive']) {
                            redirect(base_url('/consumer/add/' . $old_customer['customer']['id']));
                        } else {
                            $this->load->model('customer_level_model');
                            $level2_data = $this->customer_level_model->get(2);
                            $member_discount = $level2_data['discount'];
                            $customer = [
                                'old_customer_id' => $old_customer_id,
                                'isDealer' => 0,
                                'name' => $old_customer['name'],
                                'gender' => $old_customer['gender'],
                                'phone' => $old_customer['phone'],
                                'address' => $old_customer['address'],
                                'email' => $old_customer['email'],
                                'level' => [
                                    'title' => $level2_data['title'],
                                ],
                                'created_at' => date('Y-m-d H:i:s'),
                            ];
                        }
                    }
                } else {
                    show_error('查無舊有會員');
                }
            } elseif ($customer_id) {
                $this->customer_lib->setCustomerID($customer_id);
                $this->customer_lib->downgradeCheckCustomerLevel();
                $customer = $this->customer_lib->getCustomer();
                if (!$customer) {
                    show_error('查無消費者');
                }
                if (!empty($customer['level']['discount'])) {
                    $member_discount = $customer['level']['discount'];
                }
                if ($customer['isDealer']) {
                    if (!is_null($staff_max_amount)) {
                        $season = $this->customer_lib->getCurrentSeasonRange();
                        $order_table = $this->order_model->get_table_name();
                        $total_orders_data = $this->order_model
                            ->fields('SUM(' . $order_table . '.total) as total')
                            ->where('buyer_type', 'customer')
                            ->where('buyer_id', $customer_id)
                            ->where('created_at', '>=', $season[0])
                            ->where('created_at', '<=', $season[1])
                            ->get();
                        if ($total_orders_data) {
                            if ($staff_max_amount >= $total_orders_data['total']) {
                                $staff_max_amount -= $total_orders_data['total'];
                            } else {
                                $staff_max_amount = 0;
                            }
                        }
                    }
                }
            }
        }

        $promotes = $this->promote_model->getActivePromotes($this->dealer['retailer_id'], $customer);
        $products = $this->product_model->getCustomerProducts();
        $_combos = $this->combo_model
            ->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'pao']]])
            ->get_all();

        $_free_packages = $this->free_package_item_model
            ->with_product(['with' => ['relation' => 'pao']])
            ->get_all();

        $combos = [];
        $free_packages = [];
        if ($this->dealer['hasStock']) {
            foreach ($products as $product_id => $product) {
                $stocks = $this->stock_model
                    ->where('product_id', $product_id)
                    ->where('retailer_id', $this->dealer['retailer_id'])
                    ->where('stock', '>', 0)
                    ->group_start()
                    ->where('expired_at', '>=', date('Y-m-d'), true)
                    ->where('expired_at IS NULL', null, null, true, false, true)
                    ->group_end()
                    ->order_by('ISNULL(expired_at)', 'asc')
                    ->order_by('expired_at', 'asc')
                    ->get_all();

                $product_stock = $this->product_model->calcStock($stocks, $product);
                $products[$product_id]['expired_at'] = empty($stocks[0]['expired_at']) ? '' : $stocks[0]['expired_at'];
                $products[$product_id]['stock'] = $product_stock['active_total'];
            }

            if ($_combos) {
                foreach ($_combos as $combo) {
                    $combo_max_stock = null;
                    foreach ($combo['items'] as $key => $item) {
                        $stocks = $this->stock_model
                            ->where('product_id', $item['product_id'])
                            ->where('retailer_id', $this->dealer['retailer_id'])
                            ->where('stock', '>', 0)
                            ->order_by('expired_at', 'asc')
                            ->get_all();

                        $combo['items'][$key]['stock'] = $this->product_model->calcStock($stocks, $item['product']);

                        if (is_null($combo_max_stock)) {
                            $combo_max_stock = $combo['items'][$key]['stock']['active_total'];
                        } else {
                            $combo_max_stock = min($combo_max_stock, $combo['items'][$key]['stock']['active_total']);
                        }
                    }

                    $combo['stock'] = $combo_max_stock ? $combo_max_stock : 0;
                    $combos[$combo['id']] = $combo;
                }
            }

            if ($_free_packages) {
                foreach ($_free_packages as $free_package) {
                    $stocks = $this->stock_model
                        ->where('product_id', $free_package['product_id'])
                        ->where('retailer_id', $this->dealer['retailer_id'])
                        ->where('stock', '>', 0)
                        ->order_by('expired_at', 'asc')
                        ->get_all();

                    $product_stock = $this->product_model->calcStock($stocks, $free_package['product']);

                    $free_package['stock'] = $product_stock['active_total'];

                    $free_packages[$free_package['product_id']] = $free_package;
                }
            }
        }

        $shipout_retailers = [];
        if ($this->dealer['retailer_role_id'] == 4) {
            $this->load->library('purchase_lib');
            $purchase_lib = new purchase_lib();
            $shipout_retailers = $this->purchase_lib->getShipOutList($this->dealer['retailer_id']);
            if (!$shipout_retailers) {
                unset($this->payment_type[5]);
            }
        } else {
            unset($this->payment_type[5]);
        }

        if ($this->input->post()) {
            if (!empty($customer['customer_level_id']) || $old_customer) {
                $this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
                $this->form_validation->set_rules('phone', '電話', 'required|is_natural|max_length[20]|valid_custom_phone[' . $customer_id . ']');
                $this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
                $this->form_validation->set_rules('birthday_year', '生日年', 'integer|max_length[4]|min_length[4]');
                $this->form_validation->set_rules('birthday', '生日', 'required|valid_date');
                $this->form_validation->set_rules('email', 'Email', 'max_length[100]|valid_email');
                $this->form_validation->set_rules('address', '聯絡地址', 'required|max_length[100]');
            } else {
                if (!empty($_POST['hide_customer_info'])) {
                    $this->form_validation->set_rules('reason', '顧客為何無留下完整資料', 'required|min_length[10]|max_length[50]');
                } else {
                    $this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
                    $this->form_validation->set_rules('phone', '電話', 'required|is_natural|max_length[20]|valid_custom_phone[' . $customer_id . ']');
                    $this->form_validation->set_rules('gender', '性別', 'integer|in_list[0,1]');
                    $this->form_validation->set_rules('birthday_year', '生日年', 'integer|max_length[4]|min_length[4]');
                    $this->form_validation->set_rules('birthday', '生日', 'valid_date');
                    $this->form_validation->set_rules('email', 'Email', 'max_length[100]|valid_email');
                    $this->form_validation->set_rules('address', '聯絡地址', 'required|max_length[100]');
                }
            }

            $this->form_validation->set_rules('altAddress', '收貨地址', 'max_length[100]');
            $this->form_validation->set_rules('isDealer', '是否員工', 'integer');
            $this->form_validation->set_rules('coupon_number_1', '滿$2000核發折價券', 'max_length[30]|callback_check_coupon');
            $this->form_validation->set_rules('coupon_number_2', '滿$6000核發折價券', 'max_length[30]|callback_check_coupon');
            $this->form_validation->set_rules('payment_type', '付款方式', 'required|integer|in_list[' . implode(',', array_keys($this->payment_type)) . ']');
            if (!empty($_POST['payment_type'])) {
                if ($_POST['payment_type'] == '4') { //貨到付款
                    $this->form_validation->set_rules('recipient_name', '收件人姓名', 'required|max_length[20]');
                    $this->form_validation->set_rules('recipient_phone', '收件人電話', 'required|is_natural|max_length[20]');
                    $this->form_validation->set_rules('recipient_address', '收件人地址', 'required|max_length[100]');
                } elseif ($_POST['payment_type'] == '5') { //其他門市取貨
                    $this->form_validation->set_rules('shipout_retailer_id', '取貨門市', 'required|integer|in_list[' . implode(',', array_keys($shipout_retailers)) . ']');
                }
            }

            $check_qty_options = [
                'products' => $products,
                'items' => $this->input->post('items'),
                'expired_dates' => $this->input->post('expired_dates'),
                'combos' => $combos,
                'combo_items' => $this->input->post('combo_items'),
                'packages' => $free_packages,
                'package_items' => $this->input->post('package_items'),
                'payment_type' => $this->input->post('payment_type'),
            ];

            $promote_types = [];
            if (!empty($_POST['promote_type'])) {
                $promote_types = (array)$_POST['promote_type'];
                if ($promote_types) {
                    if (in_array(1, $promote_types)) { //會員優惠
                        $discount = $member_discount;
                    }
                    if (in_array(2, $promote_types)) { //優惠活動
                        $this->form_validation->set_rules('promote_id', '優惠活動', 'required|integer|callback_check_promote[' . json_encode(['isDealer' => $this->input->post('isDealer'), 'promotes' => $promotes]) . ']');
                        $check_qty_options['gift_items'] = $this->input->post('gift_items');
                        $check_qty_options['promotes'] = $promotes;
                        $check_qty_options['promote_id'] = $this->input->post('promote_id');
                    }
                    if (in_array(3, $promote_types)) { //使用貴賓優惠券
                        $this->form_validation->set_rules('coupon_used', '使用貴賓優惠券', 'required|max_length[30]');
                    }
                }
            }

            $this->form_validation->set_rules('items[][qty]', '貨品訂購數量', 'callback_check_qty[' . json_encode($check_qty_options) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $buyer_name = $this->input->post('name');
                $buyer_phone = $this->input->post('phone');
                $buyer_address = $this->input->post('address');
                $isDealer = empty($this->input->post('isDealer')) ? 0 : 1;

                if (!empty($customer['id'])) {
                    $customer_id = $customer['id'];
                    $update_data = [
                        'isDealer' => $isDealer,
                        'name' => $buyer_name,
                        'gender' => $this->input->post('gender') !== '' ? $this->input->post('gender') : null,
                        'birthday_year' => $this->input->post('birthday_year') ? $this->input->post('birthday_year') : null,
                        'birthday' => $this->input->post('birthday') ? date('Y') . '-' . $this->input->post('birthday') : null,
                        'email' => $this->input->post('email') ? $this->input->post('email') : null,
                        'phone' => $buyer_phone,
                        'address' => $buyer_address,
                    ];
                    $this->customer_model->update($update_data, ['id' => $customer_id]);
                } else {
                    if ($buyer_name && $buyer_phone && $buyer_address) {
                        $insert_data = [
                            'isDealer' => $isDealer,
                            'name' => $buyer_name,
                            'gender' => $this->input->post('gender') !== '' ? $this->input->post('gender') : null,
                            'birthday_year' => $this->input->post('birthday_year') ? $this->input->post('birthday_year') : null,
                            'birthday' => $this->input->post('birthday') ? date('Y') . '-' . $this->input->post('birthday') : null,
                            'email' => $this->input->post('email') ? $this->input->post('email') : null,
                            'phone' => $buyer_phone,
                            'address' => $buyer_address,
                        ];

                        //舊有會員轉換
                        if ($old_customer) {
                            $insert_data['old_customer_id'] = $old_customer_id;
                        }

                        $customer_id = $this->customer_model->insert($insert_data);
                    }
                }

                $this->load->model('order_contact_model');
                $this->load->model('order_item_model');
                $this->load->model('coupon_approve_model');

                $orderSerialNum = $this->order_model->getNextOrderSerialNum();

                $isPaid = 0;
                $isShipped = 0;
                switch ($this->input->post('payment_type')) {
                    case 4:
                        break;
                    case 5:
                        $isPaid = 1;
                        break;
                    default:
                        $isPaid = 1;
                        $isShipped = 1;
                        break;
                }

                $memo = null;
                if (!empty($_POST['hide_customer_info'])) {
                    $memo = $this->input->post('reason');
                }
                if ($this->input->post('memo')) {
                    if ($memo) {
                        $memo .= PHP_EOL;
                    }
                    $memo .= $this->input->post('memo');
                }

                $orderNum = date('Ym') . $orderSerialNum;
                $order_id = $this->order_model->insert([
                    'buyer_type' => 'customer',
                    'buyer_id' => $customer_id ? $customer_id : null,
                    'shipout_retailer_id' => $this->dealer['retailer_id'],
                    'serialNum' => $orderSerialNum,
                    'orderNum' => $orderNum,
                    'couponNum' => empty($this->input->post('coupon_used')) ? null : $this->input->post('coupon_used'),
                    'dealer_id' => $this->dealer['id'],
                    'isConfirmed' => 1,
                    'isPaid' => $isPaid,
                    'isShipped' => $isShipped,
                    'memo' => $memo,
                ]);

                if ($customer_id) {
                    $this->order_contact_model->insert([
                        'order_id' => $order_id,
                        'name' => $buyer_name,
                        'phone' => $buyer_phone,
                        'address' => $this->input->post('address') ? $this->input->post('address') : null,
                        'altAddress' => $this->input->post('altAddress') ? $this->input->post('altAddress') : null,
                    ]);
                }

                if ($this->input->post('payment_type') == '4') { //貨到付款
                    $this->load->model('order_recipient_model');
                    $this->order_recipient_model->insert([
                        'order_id' => $order_id,
                        'name' => $this->input->post('recipient_name'),
                        'phone' => $this->input->post('recipient_phone'),
                        'address' => $this->input->post('recipient_address'),
                    ]);
                }

                //出貨
                if ($isShipped) {
                    $shipment_id = $this->shipment_model->insert([
                        'ship_type' => 'consumer',
                        'ship_id' => $order_id,
                        'shipout_retailer_id' => $this->dealer['retailer_id'],
                        'shipin_retailer_id' => null,
                        'eta_at' => date('Y-m-d'),
                        'memo' => null,
                        'isConfirmed' => 1,
                        'retailer_id' => $this->dealer['retailer_id'],
                        'dealer_id' => $this->dealer['id'],
                    ]);

                    //紀錄產品有效期限
                    $expired_dates = (array)$this->input->post('expired_dates');
                    $expired_at_data = [];
                    foreach ($expired_dates as $product_id => $expired_date) {
                        if (!isset($expired_at_data[$product_id])) {
                            $expired_at_data[$product_id] = [];
                        }
                        foreach ($expired_date as $expired_at) {
                            if (!isset($expired_at_data[$product_id][$expired_at])) {
                                $expired_at_data[$product_id][$expired_at] = 0;
                            }
                            $expired_at_data[$product_id][$expired_at]++;
                        }
                    }

                    foreach ($expired_at_data as $product_id => $v) {
                        foreach ($v as $expired_at => $q) {
                            $this->shipment_expiration_model->insert([
                                'shipment_id' => $shipment_id,
                                'product_id' => $product_id,
                                'expired_at' => $expired_at ? $expired_at : null,
                                'qty' => $q,
                            ]);
                        }
                    }
                }

                $promote = [];
                if (in_array(2, $promote_types)) { //優惠活動
                    $promote_id = (int)$this->input->post('promote_id');
                    $promote = (isset($promotes[$promote_id])) ? $promotes[$promote_id] : [];
                    if ($promote) {
                        $this->promote_use_model->insert([
                            'promote_id' => $promote_id,
                            'customer_id' => $customer_id,
                        ]);
                    }
                }

                $items = (array)$this->input->post('items');
                $combo_items = (array)$this->input->post('combo_items');
                $package_items = (array)$this->input->post('package_items');
                $subtotal = 0;
                $total = 0;
                $totalDiscount = 0;
                $totalReachDiscount = 0;

                if ($items) {
                    foreach ($items as $product_id => $item) {
                        if (!$item['qty']) continue;
                        $item_discount = $discount;
                        $item_discount_type = $discount_type;
                        $price = $products[$product_id]['pdCash'];
                        $item_subtotal = $item['qty'] * $price;

                        if ($item_discount_type == 'P') {
                            $item_total = round($item_subtotal * $item_discount / 100);
                        } else {
                            $item_total = $item_subtotal - $item_discount;
                            $item_discount = round($item_total / $item_subtotal * 100);
                        }

                        if ($promote) {
                            foreach ($promote['methods'] as $key => $method) {
                                switch ($method['promote_type_id']) {
                                    case 1: //產品折扣
                                        $item_match = false;
                                        if (empty($method['items'])) {
                                            $item_match = true;
                                        } else {
                                            foreach ($method['items'] as $pitem) {
                                                if ($pitem['id'] == $product_id) {
                                                    $item_match = true;
                                                    break;
                                                }
                                            }
                                        }

                                        if ($item_match) {
                                            if ($method['discount_type'] == 'P') {
                                                $item_total = round($item_total * $method['discount'] / 100);
                                                $item_discount = round($item_total / $item_subtotal * 100);
                                            } else {
                                                $item_total -= $method['discount'];
                                                $item_discount = round($item_total / $item_subtotal * 100);
                                            }
                                        }
                                        break;
                                    case 2: //滿額折扣
                                        $item_match = false;
                                        if (!empty($method['items'])) {
                                            foreach ($method['items'] as $pitem) {
                                                if ($pitem['id'] == $product_id) {
                                                    $item_match = true;
                                                    break;
                                                }
                                            }
                                        } else {
                                            $item_match = true;
                                        }

                                        if ($item_match) {
                                            if (!isset($promote['methods'][$key]['totalDiscount'])) {
                                                $promote['methods'][$key]['totalDiscount'] = 0;
                                            }
                                            $promote['methods'][$key]['totalDiscount'] += $item_total;
                                        }
                                        break;
                                    case 3: //贈品
                                        $item_match = false;
                                        if (!empty($method['relatives'])) {
                                            foreach ($method['relatives'] as $pitem) {
                                                if ($pitem['type'] == 'product' && $pitem['id'] == $product_id) {
                                                    $item_match = true;
                                                    break;
                                                }
                                            }
                                        } else {
                                            $item_match = true;
                                        }

                                        if ($item_match) {
                                            if (!isset($promote['methods'][$key]['totalGift'])) {
                                                $promote['methods'][$key]['totalGift'] = 0;
                                            }
                                            $promote['methods'][$key]['totalGift'] += $item_total;
                                        }
                                        break;
                                }
                            }
                        }

                        $this->order_item_model->insert([
                            'order_id' => $order_id,
                            'product_id' => $product_id,
                            'qty' => $item['qty'],
                            'price' => $price,
                            'discount' => $item_discount,
                            'subPrice' => $item_total,
                        ]);

                        if ($isShipped) {
                            $this->shipment_item_model->insert([
                                'shipment_id' => $shipment_id,
                                'product_id' => $product_id,
                                'qty' => $item['qty'],
                            ]);
                        }

                        $subtotal += $item_subtotal;
                        $totalDiscount += $item_subtotal - $item_total;
                        $total += $item_total;
                    }
                }

                if ($combo_items) {
                    foreach ($combo_items as $combo_id => $item) {
                        foreach ($combos[$combo_id]['items'] as $citem) {
                            if (!$citem['qty']) continue;
                            $combo_item_discount = $discount;
                            $combo_item_discount_type = $discount_type;
                            $combo_item_qty = $citem['qty'] * $item['qty'];
                            $combo_item_subtotal = $combo_item_qty * $citem['price'];

                            if ($combo_item_discount_type == 'P') {
                                $combo_item_total = round($combo_item_subtotal * $combo_item_discount / 100);
                            } else {
                                $combo_item_total = $combo_item_subtotal - $combo_item_discount;
                                $combo_item_discount = round($combo_item_total / $combo_item_subtotal * 100);
                            }

                            if ($promote) {
                                foreach ($promote['methods'] as $key => $method) {
                                    switch ($method['promote_type_id']) {
                                        case 1: //產品折扣
                                            $item_match = false;
                                            if (!empty($method['items'])) {
                                                foreach ($method['items'] as $pitem) {
                                                    if ($pitem['type'] == 'combo' && $pitem['id'] == $combo_id) {
                                                        $item_match = true;
                                                        break;
                                                    }
                                                }
                                            } else {
                                                $item_match = true;
                                            }

                                            if ($item_match) {
                                                if ($method['discount_type'] == 'P') {
                                                    $combo_item_total = round($combo_item_total * $method['discount'] / 100);
                                                    if ($combo_item_subtotal > 0) {
                                                        $combo_item_discount = round($combo_item_total / $combo_item_subtotal * 100);
                                                    }
                                                } else {
                                                    $combo_item_total -= $method['discount'];
                                                    if ($combo_item_subtotal > 0) {
                                                        $combo_item_discount = round($combo_item_total / $combo_item_subtotal * 100);
                                                    }
                                                }
                                            }
                                            break;
                                        case 2: //滿額折扣
                                            $item_match = false;
                                            if (!empty($method['items'])) {
                                                foreach ($method['items'] as $pitem) {
                                                    if ($pitem['type'] == 'combo' && $pitem['id'] == $combo_id) {
                                                        $item_match = true;
                                                        break;
                                                    }
                                                }
                                            } else {
                                                $item_match = true;
                                            }

                                            if ($item_match) {
                                                if (!isset($promote['methods'][$key]['totalDiscount'])) {
                                                    $promote['methods'][$key]['totalDiscount'] = 0;
                                                }
                                                $promote['methods'][$key]['totalDiscount'] += $combo_item_total;
                                            }
                                            break;
                                        case 3: //贈品
                                            $item_match = false;
                                            if (!empty($method['relatives'])) {
                                                foreach ($method['relatives'] as $pitem) {
                                                    if ($pitem['type'] == 'combo' && $pitem['id'] == $combo_id) {
                                                        $item_match = true;
                                                        break;
                                                    }
                                                }
                                            } else {
                                                $item_match = true;
                                            }

                                            if ($item_match) {
                                                if (!isset($promote['methods'][$key]['totalGift'])) {
                                                    $promote['methods'][$key]['totalGift'] = 0;
                                                }
                                                $promote['methods'][$key]['totalGift'] += $combo_item_total;
                                            }
                                            break;
                                    }
                                }
                            }

                            $this->order_item_model->insert([
                                'order_id' => $order_id,
                                'product_id' => $citem['product_id'],
                                'qty' => $combo_item_qty,
                                'price' => $citem['price'],
                                'discount' => $combo_item_discount,
                                'subPrice' => $combo_item_total,
                            ]);

                            if ($isShipped) {
                                $this->shipment_item_model->insert([
                                    'shipment_id' => $shipment_id,
                                    'product_id' => $citem['product_id'],
                                    'qty' => $combo_item_qty,
                                ]);
                            }

                            $subtotal += $combo_item_subtotal;
                            $totalDiscount += $combo_item_subtotal - $combo_item_total;
                            $total += $combo_item_total;
                        }
                    }
                }

                if ($package_items) {
                    foreach ($package_items as $product_id => $item) {
                        $this->order_item_model->insert([
                            'order_id' => $order_id,
                            'product_id' => $product_id,
                            'qty' => $item['qty'],
                            'price' => 0,
                            'discount' => 100,
                            'subPrice' => 0,
                        ]);

                        if ($isShipped) {
                            $this->shipment_item_model->insert([
                                'shipment_id' => $shipment_id,
                                'product_id' => $product_id,
                                'qty' => $item['qty'],
                            ]);
                        }
                    }
                }

                if ($promote) {
                    foreach ($promote['methods'] as $method) {
                        switch ($method['promote_type_id']) {
                            case 2: //滿額折扣
                                if (isset($method['totalDiscount']) && $method['totalDiscount'] >= $method['limit']) {
                                    $totalReachDiscount += $method['discount'];
                                }
                                break;
                            case 3: //贈品
                                if (isset($method['totalGift']) && $method['totalGift'] >= $method['limit']) {
                                    $options = $method['options'];
                                    if (empty($options['single'])) {
                                        foreach ($method['items'] as $pitem) {
                                            if ($pitem['type'] == 'product') {
                                                $this->order_item_model->insert([
                                                    'order_id' => $order_id,
                                                    'product_id' => $pitem['id'],
                                                    'qty' => 1,
                                                    'price' => 0,
                                                    'discount' => 100,
                                                    'subPrice' => 0,
                                                ]);

                                                if ($isShipped) {
                                                    $this->shipment_item_model->insert([
                                                        'shipment_id' => $shipment_id,
                                                        'product_id' => $pitem['id'],
                                                        'qty' => 1,
                                                    ]);
                                                }
                                            } elseif ($pitem['type'] == 'combo') {
                                                foreach ($combos[$pitem['id']]['items'] as $citem) {
                                                    $this->order_item_model->insert([
                                                        'order_id' => $order_id,
                                                        'product_id' => $citem['product_id'],
                                                        'qty' => $citem['qty'],
                                                        'price' => 0,
                                                        'discount' => 100,
                                                        'subPrice' => 0,
                                                    ]);

                                                    if ($isShipped) {
                                                        $this->shipment_item_model->insert([
                                                            'shipment_id' => $shipment_id,
                                                            'product_id' => $citem['product_id'],
                                                            'qty' => $citem['qty'],
                                                        ]);
                                                    }
                                                }
                                            }
                                        }
                                    } else { //擇一贈品
                                        $gift_items = (array)$this->input->post('gift_items');
                                        if ($gift_items && !empty($gift_items[$method['id']])) {
                                            $pitem = explode('-', $gift_items[$method['id']]);
                                            if (!empty($pitem[0]) && !empty($pitem[1])) {
                                                if ($pitem[0] == 'product') {
                                                    $this->order_item_model->insert([
                                                        'order_id' => $order_id,
                                                        'product_id' => $pitem[1],
                                                        'qty' => 1,
                                                        'price' => 0,
                                                        'discount' => 100,
                                                        'subPrice' => 0,
                                                    ]);

                                                    if ($isShipped) {
                                                        $this->shipment_item_model->insert([
                                                            'shipment_id' => $shipment_id,
                                                            'product_id' => $pitem[1],
                                                            'qty' => 1,
                                                        ]);
                                                    }
                                                } elseif ($pitem[0] == 'combo') {
                                                    foreach ($combos[$pitem[1]]['items'] as $citem) {
                                                        $this->order_item_model->insert([
                                                            'order_id' => $order_id,
                                                            'product_id' => $citem['product_id'],
                                                            'qty' => $citem['qty'],
                                                            'price' => 0,
                                                            'discount' => 100,
                                                            'subPrice' => 0,
                                                        ]);

                                                        if ($isShipped) {
                                                            $this->shipment_item_model->insert([
                                                                'shipment_id' => $shipment_id,
                                                                'product_id' => $citem['product_id'],
                                                                'qty' => $citem['qty'],
                                                            ]);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                break;
                        }
                    }

                    $total -= $totalReachDiscount;
                }

                $this->order_model->update([
                    'subtotal' => $subtotal,
                    'totalDiscount' => $totalDiscount,
                    'totalReachDiscount' => $totalReachDiscount,
                    'total' => $total,
                ], ['id' => $order_id]);

                if ($isShipped) {
                    //出貨扣庫
                    $this->stock_lib->shipout_confirm($shipment_id);
                }

                //付款紀錄
                if ($isPaid) {
                    $this->payment_model->insert([
                        'pay_type' => 'order',
                        'pay_id' => $order_id,
                        'received_retailer_id' => $this->dealer['retailer_id'],
                        'price' => $total,
                        'type_id' => $this->input->post('payment_type'),
                        'active' => 1,
                        'isConfirmed' => 1,
                        'retailer_id' => $this->dealer['retailer_id'],
                        'dealer_id' => $this->dealer['id'],
                    ]);
                }

                //核發優惠券
                if ($total >= 2000) {
                    if ($this->input->post('coupon_number_1')) {
                        $this->coupon_approve_model->insert([
                            'order_id' => $order_id,
                            'couponNum' => $this->input->post('coupon_number_1'),
                        ]);
                    }

                    if ($total >= 6000) {
                        if ($this->input->post('coupon_number_2')) {
                            $this->coupon_approve_model->insert([
                                'order_id' => $order_id,
                                'couponNum' => $this->input->post('coupon_number_2'),
                            ]);
                        }
                    }
                }

                //消費者升等
                if (!$isDealer) {
                    if ($old_customer) {
                        $this->customer_lib->setCustomerID($customer_id);
                        $this->customer_model->update([
                            'customer_level_id' => 2,
                        ], ['id' => $customer_id]);

                        $this->customer_lib->saveLevelChangeHistory(2, 1);
                    } elseif ($customer_id) {
                        $this->customer_lib->setCustomerID($customer_id);
                        $customer_level_id = $this->customer_lib->upgradeLevel();
                        if ($customer_level_id) {
                            if ($customer_level_id == 1) {
                                redirect(base_url('/customer/upgrade/' . $customer_id));
                            } else {
                                if ($customer_level_id == 2) {
                                    $this->customer_model->update([
                                        'customer_level_id' => $customer_level_id,
                                    ], ['id' => $customer_id]);
                                    $this->customer_lib->saveLevelChangeHistory(2, 1);

                                    $this->session->set_userdata(array('msg' => '已成為春水綠卡會員'));
                                } elseif ($customer_level_id == 3) {
                                    $this->customer_lib->saveLevelChangeHistory(3, 1);

                                    $this->session->set_userdata(array('msg' => '已成為曜石黑卡會員'));
                                }
                            }
                        }
                    }
                }

                //其他門市出貨
                if ($this->input->post('payment_type') == 5) {
                    $order = $this->order_model
                        ->where('buyer_type', 'customer')
                        ->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
                        ->get($order_id);

                    if ($order) {
                        $this->load->model('purchase_model');
                        $this->load->model('purchase_item_model');

                        $shipout_retailer_id = $this->input->post('shipout_retailer_id');
                        $discount = $shipout_retailers[$shipout_retailer_id]['discount'];
                        $purchaseSerialNum = $this->purchase_model->getNextPurchaseSerialNum();

                        $purchase_id = $this->purchase_model->insert([
                            'retailer_id' => $this->dealer['retailer_id'],
                            'retailer_address' => $this->dealer['address'],
                            'shipout_retailer_id' => $shipout_retailer_id,
                            'shipin_retailer_id' => $this->dealer['retailer_id'],
                            'shipin_address' => $this->dealer['address'],
                            'serialNum' => $purchaseSerialNum,
                            'purchaseNum' => date('Ym') . $purchaseSerialNum,
                            'dealer_id' => $this->dealer['id'],
                        ]);

                        $subtotal = 0;
                        $total = 0;

                        foreach ($order['items'] as $item) {
                            $qty = $item['qty'];
                            $price = $item['product']['pdCash'];

                            $this->purchase_item_model->insert([
                                'purchase_id' => $purchase_id,
                                'product_id' => $item['product_id'],
                                'price' => $price,
                                'qty' => $qty,
                                'subtotal' => $price * $qty,
                                'discount' => $discount,
                                'total' => round($price * $qty * $discount / 100),
                            ]);

                            $subtotal += $price * $qty;
                            $total += round($price * $qty * $discount / 100);
                        }

                        $this->purchase_model->update([
                            'isMatchBox' => 1,
                            'subtotal' => $subtotal,
                            'total' => $total,
                        ], ['id' => $purchase_id]);

                        $this->payment_model->insert([
                            'pay_type' => 'purchase',
                            'pay_id' => $purchase_id,
                            'paid_retailer_id' => $this->dealer['retailer_id'],
                            'received_retailer_id' => $shipout_retailer_id,
                            'price' => $total,
                            'retailer_id' => $this->dealer['retailer_id'],
                            'dealer_id' => $this->dealer['id'],
                            'active' => 0,
                        ]);

                        //新增A店買B店取貨之紀錄
                        $this->order_transfer_model->insert([
                            'order_id' => $order_id,
                            'purchase_id' => $purchase_id,
                            'retailer_id' => $this->dealer['retailer_id'],
                            'shipout_retailer_id' => $shipout_retailer_id,
                            'dealer_id' => $this->dealer['id'],
                        ]);
                    }
                }

                if ($_POST['submit_recommend']) {
                    redirect(base_url('/recommend/add'));
                } elseif ($customer_id) {
                    redirect(base_url('/customer/consumer/' . $customer_id));
                } else {
                    redirect(base_url('/consumer/overview'));
                }
            }
        }

        if ($old_customer) {
            $title = '舊有會員轉換';
        } elseif ($customer) {
            $title = '新增消費紀錄';
        } else {
            $title = '新增新消費者紀錄';
        }

        $data = [
            'isOld' => $old_customer,
            'headline' => $title,
            'customer' => $customer,
            'member_discount' => $member_discount,
            'promotes' => $promotes,
            'products' => $products,
            'combos' => $combos,
            'free_packages' => $free_packages,
            'payment_type' => $this->payment_type,
            'shipout_retailers' => $shipout_retailers,
            'staff_max_amount' => $staff_max_amount,
            'title' => $title,
            'view' => 'consumer/add',
        ];

        $this->_preload($data);
    }

    public function check_qty($i, $params)
    {
        $params = json_decode($params, true);
        $products = (array)$params['products'];
        $combos = (array)$params['combos'];
        $packages = (array)$params['packages'];
        $items = (array)$params['items'];
        $expired_dates = (array)$params['expired_dates'];
        $combo_items = (array)$params['combo_items'];
        $package_items = (array)$params['package_items'];
        $payment_type = (int)$params['payment_type'];

        $isShipped = true;
        if (in_array($payment_type, [4, 5])) {
            $isShipped = false;
        }

        if (empty($params['gift_items'])) {
            $gift_items = [];
            $promotes = [];
            $promote_id = null;
        } else {
            $gift_items = (array)$params['gift_items'];
            $promotes = (array)$params['promotes'];
            $promote_id = (int)$params['promote_id'];
        }
        $error = '';
        $selected_products = [];

        if ($combo_items) {
            foreach ($combo_items as $combo_id => $item) {
                if (!isset($combos[$combo_id])) {
                    $error = '輸入的組合產品有誤';
                    break;
                }

                $item['qty'] = (int)$item['qty'];
                if ($item['qty'] === false) {
                    $error = '輸入的組合產品數量有誤';
                    break;
                } elseif ($this->dealer['hasStock'] && $isShipped && $item['qty'] > $combos[$combo_id]['stock']) {
                    $error = '輸入的組合產品數量超過庫存上限';
                    break;
                }

                foreach ($combos[$combo_id]['items'] as $k => $citem) {
                    $selected_products = $this->calcProductQty($selected_products, $citem['product_id'], $citem['qty'] * $item['qty']);
                }
            }
        }

        if (!$error && $package_items) {
            foreach ($package_items as $product_id => $item) {
                if (!isset($packages[$product_id])) {
                    $error = '輸入的免費包裝商品有誤';
                    break;
                }

                $item['qty'] = (int)$item['qty'];
                if ($item['qty'] === false) {
                    $error = '輸入的免費包裝商品數量有誤';
                    break;
                }

                $selected_products = $this->calcProductQty($selected_products, $product_id, $item['qty']);
            }
        }

        if (!$error && $promote_id && isset($promotes[$promote_id])) {
            $hasGift = false;
            foreach ($promotes[$promote_id]['methods'] as $method) {
                if ($method['promote_type_id'] == 3) {
                    $options = $method['options'];

                    if (!empty($options['single'])) { //擇一贈品
                        if ($gift_items && !empty($gift_items[$method['id']])) {
                            $pitem = explode('-', $gift_items[$method['id']]);
                        }
                    }

                    foreach ($method['items'] as $item) {
                        if (empty($options['single']) || (!empty($pitem[0]) && !empty($pitem[1]) && $item['type'] == $pitem[0] && $item['id'] == $pitem[1])) {
                            if ($item['type'] == 'product') {
                                $selected_products = $this->calcProductQty($selected_products, $item['id'], $item['qty']);
                            } elseif ($item['type'] == 'combo') {
                                if (!empty($combos[$item['id']])) {
                                    foreach ($combos[$item['id']]['items'] as $k => $citem) {
                                        $selected_products = $this->calcProductQty($selected_products, $citem['product_id'], $citem['qty']);
                                    }
                                } else {
                                    $error = '贈品中的組合商品有誤';
                                }
                            }

                            $hasGift = true;
                        }
                    }
                }
            }

            if (!$hasGift) {
                $error = '贈品選擇錯誤';
            }
        }

        if (!$error && $items) {
            foreach ($items as $product_id => $item) {
                if (!isset($products[$product_id])) {
                    $error = '輸入的貨品有誤';
                    break;
                }

                $item['qty'] = (int)$item['qty'];
                if ($item['qty'] === false) {
                    $error = '輸入的貨品數量有誤';
                    break;
                }

                $selected_products = $this->calcProductQty($selected_products, $product_id, $item['qty']);
            }
        }


        if (!$error) {
            if (!$selected_products) {
                $error = '您尚未選購商品';
            }
        }

        if (!$error && $this->dealer['hasStock'] && $isShipped) {
            foreach ($selected_products as $product_id => $qty) {
                if (isset($expired_dates[$product_id])) {
                    if (count($expired_dates[$product_id]) == $qty) {
                        $expired_at_data = [];
                        foreach ($expired_dates[$product_id] as $expired_at) {
                            if (!isset($expired_at_data[$expired_at])) {
                                $expired_at_data[$expired_at] = 0;
                            }
                            $expired_at_data[$expired_at]++;
                        }

                        foreach ($expired_at_data as $expired_at => $q) {
                            if ($expired_at) {
                                $this->stock_model
                                    ->where('expired_at', $expired_at)
                                    ->where('expired_at', '>=', date('Y-m-d'));
                            } else {
                                $this->stock_model->where('expired_at IS NULL', null, null, false, false, true);
                            }

                            $stock = $this->stock_model
                                ->where('product_id', $product_id)
                                ->where('retailer_id', $this->dealer['retailer_id'])
                                ->where('stock', '>=', $q)
                                ->get();

                            if (!$stock) {
                                $error = '輸入的商品有效期限不符或不足';
                                break;
                            }
                        }
                    } else {
                        $error = '商品數量與輸入的商品有效期限數量不符';
                        break;
                    }
                } else {
                    $error = '您尚未填寫商品有效期限';
                    break;
                }

            }
        }

        if (!$error) {
            return true;
        } else {
            $this->form_validation->set_message('check_qty', $error);
            return false;
        }
    }

    protected function calcProductQty($selected_products, $product_id, $qty)
    {
        if (!isset($selected_products[$product_id])) {
            $selected_products[$product_id] = 0;
        }
        $selected_products[$product_id] += $qty;

        return $selected_products;
    }

    public function check_promote($promote_id, $params)
    {
        $params = json_decode($params, true);
        $isDealer = $params['isDealer'];
        $promotes = $params['promotes'];

        foreach ($promotes as $promote) {
            if ($promote['id'] == $promote_id) {
                switch ($promote['customer_type']) {
                    case 3:
                        if ($isDealer) {
                            return true;
                        }
                        break;
                    default:
                        return true;
                        break;
                }
            }
        }

        $this->form_validation->set_message('check_promote', '優惠活動選擇錯誤');
        return false;
    }

    //檢查核發優惠券是否重複
    public function check_coupon($couponNum)
    {
        if ($couponNum) {
            $this->load->model('coupon_approve_model');
            $coupon_count = $this->coupon_approve_model
                ->where('couponNum', $couponNum)
                ->count_rows();

            if ($coupon_count) {
                $this->form_validation->set_message('check_coupon', '折價券編號重複');
                return false;
            }
        }

        return true;
    }

    public function edit($order_id)
    {
        $order = $this->order_model
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->with_shipment('fields:ctName')
            ->get($order_id);

        if (!$order_id || !$order) {
            show_error('查無消費紀錄');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('created_at', '訂單日期', 'required|valid_date');

            if ($this->form_validation->run() !== FALSE) {
                $this->order_model->update([
                    'created_at' => $this->input->post('created_at'),
                ], ['id' => $order_id]);

                redirect(base_url('/consumer/overview'));
            }
        }

        $data = [
            'order' => $order,
            'title' => '編輯消費紀錄',
            'view' => 'consumer/edit',
        ];

        $this->_preload($data);
    }

    public function cancel($order_id)
    {
        $order = $this->order_model
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->with_shipment('fields:ctName')
            ->get($order_id);

        if (!$order_id || !$order) {
            show_error('查無消費紀錄');
        }

        $this->order_model->delete($order_id);

        //刪除付款
        $payment = $this->payment_model
            ->where('pay_type', 'order')
            ->where('pay_id', $order_id)
            ->where('received_retailer_id', $this->dealer['retailer_id'])
            ->get();
        if ($payment) {
            $this->payment_model->delete($payment['id']);
        }

        //刪除出貨
        $shipment = $this->shipment_model
            ->where('ship_type', 'consumer')
            ->where('ship_id', $order_id)
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get();
        if ($shipment) {
            //出貨扣庫恢復
            $this->stock_lib->shipout_rollback($shipment['id']);
            $this->shipment_model->delete($shipment['id']);

            $this->order_model->update(['isShipped' => 0, 'dealer_id' => $this->dealer['id']], ['id' => $order_id]);
        }

        redirect(base_url('/consumer/overview'));
    }

    public function recover($order_id)
    {
        $order = $this->order_model
            ->only_trashed()
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->with_shipment('fields:ctName')
            ->get($order_id);

        if (!$order_id || !$order) {
            show_error('查無消費紀錄');
        }

        $this->order_model->delete($order_id);

        //刪除付款恢復
        $payment = $this->payment_model
            ->only_trashed()
            ->where('pay_type', 'order')
            ->where('pay_id', $order_id)
            ->where('received_retailer_id', $this->dealer['retailer_id'])
            ->get();
        if ($payment) {
            $this->payment_model->restore($payment['id']);
        }

        //刪除出貨恢復
        $shipment = $this->shipment_model
            ->only_trashed()
            ->where('ship_type', 'consumer')
            ->where('ship_id', $order_id)
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get();
        if ($shipment) {
            $this->shipment_model->restore($shipment['id']);
            $this->stock_lib->shipout_confirm($shipment['id']);

            $this->order_model->update(['isShipped' => 0, 'dealer_id' => $this->dealer['id']], ['id' => $order_id]);
        }

        $this->order_model->update(
            [
                'dealer_id' => $this->dealer['id'],
                'deleted_at' => null
            ], ['id' => $order_id]);

        redirect(base_url('/consumer/trashed'));
    }


    public function payAtShipped()
    {
        $total_orders_count = $this->order_model
            ->with_payments(['where' => "type_id=4"])//貨到付款
            ->with_shipments()
            ->with_returns()
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->count_rows();

        $orders = $this->order_model
            ->with_payments(['where' => "type_id=4"])
            ->with_shipments()
            ->with_returns()
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->order_by('id', 'desc')
            ->paginate(20, $total_orders_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('consumer', 'detail')) {
            $authority['detail'] = true;
        }
        if ($this->authentic->authority('consumer', 'shipping')) {
            $authority['shipping'] = true;
        }
        if ($this->authentic->authority('consumer', 'paying')) {
            $authority['paying'] = true;
        }
        if ($this->authentic->authority('consumer', 'reject')) {
            $authority['reject'] = true;
        }
        if ($this->authentic->authority('consumer', 'orderReturn')) {
            $authority['orderReturn'] = true;
        }

        $data = [
            'orders' => $orders,
            'pagination' => $this->order_model->all_pages,
            'authority' => $authority,
            'title' => '貨到付款管理',
            'view' => 'consumer/pay_at_shipped',
        ];

        $this->_preload($data);
    }

    public function shipping($order_id)
    {
        $order = $this->order_model
            ->with_items()
            ->with_shipments()
            ->with_recipient()
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get($order_id);

        if (!$order) {
            show_error('查無訂單資料');
        }

        if (!empty($order['shipments'])) {
            $last_shipment = end($order['shipments']);
            if ($last_shipment['isConfirmed']) {
                show_error('此訂單已出貨');
            } elseif ($last_shipment['isConfirmed'] === '0') {  //拒絕收貨
                if (!empty($order['returns'])) {
                    show_error('此訂單已退貨');
                }
            }
        }

        $this->load->model('order_item_model');
        $items = $this->order_item_model
            ->with_product()
            ->where('order_id', $order_id)
            ->get_all();

        if (!$items) {
            show_error('訂單無商品資料');
        } else {
            $products = [];

            foreach ($items as $item) {
                if (!isset($products[$item['product_id']])) {
                    $stocks = $this->stock_model
                        ->where('product_id', $item['product_id'])
                        ->where('retailer_id', $this->dealer['retailer_id'])
                        ->where('stock', '>', 0)
                        ->group_start()
                        ->where('expired_at', '>=', date('Y-m-d'), true)
                        ->where('expired_at IS NULL', null, null, true, false, true)
                        ->group_end()
                        ->order_by('ISNULL(expired_at)', 'asc')
                        ->order_by('expired_at', 'asc')
                        ->get_all();

                    $products[$item['product_id']] = [
                        'name' => $item['product']['pdName'] . $item['product']['intro2'],
                        'qty' => 0,
                        'stocks' => $stocks,
                    ];
                }
                $products[$item['product_id']]['qty'] += $item['qty'];
            }
        }

        $error = [];
        if ($this->input->post()) {
            $this->form_validation->set_rules('fare', '手續費', 'required|integer|greater_than_equal_to[0]');
            $this->form_validation->set_rules('freight', '運費', 'required|integer|greater_than_equal_to[0]');

            $check_expired_options = [
                'products' => $products,
                'items' => $this->input->post('items'),
            ];

            $this->form_validation->set_rules('items', '出貨數量', 'callback_check_shipping_qty[' . json_encode($check_expired_options) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $product_verify = null;
                $fare_verify = null;
                $shipment_verify = null;

                if (!empty($_FILES)) {
                    $config['upload_path'] = FCPATH . 'uploads/';
                    $config['allowed_types'] = 'gif|jpg|png';
                    $config['max_size'] = 10000000; //10M
                    $config['file_ext_tolower'] = true;
                    $config['encrypt_name'] = true;
                    $this->load->library('upload', $config);

                    if ($_FILES['product_verify'] && $_FILES['product_verify']['size']) {
                        if ($this->upload->do_upload('product_verify')) {
                            $upload_data = $this->upload->data();
                            $product_verify = '/uploads/' . $upload_data['file_name'];
                        } else {
                            $error[] = strip_tags($this->upload->display_errors());
                        }
                    }

                    if ($_FILES['fare_verify'] && $_FILES['fare_verify']['size']) {
                        if ($this->upload->do_upload('fare_verify')) {
                            $upload_data = $this->upload->data();
                            $fare_verify = '/uploads/' . $upload_data['file_name'];
                        } else {
                            $error[] = strip_tags($this->upload->display_errors());
                        }
                    }

                    if ($_FILES['shipment_verify'] && $_FILES['shipment_verify']['size']) {
                        if ($this->upload->do_upload('shipment_verify')) {
                            $upload_data = $this->upload->data();
                            $shipment_verify = '/uploads/' . $upload_data['file_name'];
                        } else {
                            $error[] = strip_tags($this->upload->display_errors());
                        }
                    }
                }

                $shipment_id = $this->shipment_model->insert([
                    'ship_type' => 'consumer',
                    'ship_id' => $order_id,
                    'shipout_retailer_id' => $this->dealer['retailer_id'],
                    'shipin_retailer_id' => null,
                    'eta_at' => date('Y-m-d'),
                    'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
                    'product_verify' => $product_verify,
                    'fare_verify' => $fare_verify,
                    'shipment_verify' => $shipment_verify,
                    'retailer_id' => $this->dealer['retailer_id'],
                    'dealer_id' => $this->dealer['id'],
                ]);

                foreach ($order['items'] as $item) {
                    $this->shipment_item_model->insert([
                        'shipment_id' => $shipment_id,
                        'product_id' => $item['product_id'],
                        'qty' => $item['qty'],
                    ]);
                }

                //紀錄產品有效期限
                $items = (array)$this->input->post('items');
                foreach ($items as $product_id => $expired_data) {
                    foreach ($expired_data as $expired_at => $qty) {
                        if ($qty > 0) {
                            $this->shipment_expiration_model->insert([
                                'shipment_id' => $shipment_id,
                                'product_id' => $product_id,
                                'expired_at' => $expired_at ? $expired_at : null,
                                'qty' => $qty,
                            ]);
                        }
                    }
                }

                //出貨扣庫
                $this->stock_lib->shipout_confirm($shipment_id);

                $this->order_model->update(['isShipped' => 1, 'dealer_id' => $this->dealer['id']], ['id' => $order_id]);

                //運費
                $this->load->model('expense_model');
                $fare = $this->input->post('fare');
                $freight = $this->input->post('freight');
                if ($fare > 0) {
                    $this->expense_model->insert([
                        'retailer_id' => $this->dealer['retailer_id'],
                        'event_type' => 'shipment',
                        'event_id' => $shipment_id,
                        'expense_type' => 'fare',
                        'price' => $fare,
                        'dealer_id' => $this->dealer['id'],
                    ]);
                }

                if ($freight > 0) {
                    $this->expense_model->insert([
                        'retailer_id' => $this->dealer['retailer_id'],
                        'event_type' => 'shipment',
                        'event_id' => $shipment_id,
                        'expense_type' => 'freight',
                        'price' => $freight,
                        'dealer_id' => $this->dealer['id'],
                    ]);
                }

                redirect(base_url('/consumer/payAtShipped/'));
            }
        }

        $data = [
            'order' => $order,
            'products' => $products,
            'error' => $error,
            'title' => '貨到付款確認寄出',
            'view' => 'consumer/shipping',
        ];

        $this->_preload($data);
    }

    public function check_shipping_qty($i, $params)
    {
        $params = json_decode($params, true);
        $products = (array)$params['products'];
        $items = (array)$params['items'];
        $error = '';

        if (!$items) {
            $error = '無輸入任何商品';
        } else {
            foreach ($items as $product_id => $expired_data) {
                if (!isset($products[$product_id])) {
                    $error = '輸入的商品有誤';
                    break;
                }

                $shipping_qty = 0;
                foreach ($expired_data as $expired_at => $qty) {
                    if ($qty > 0) {
                        $match_stock = false;
                        foreach ($products[$product_id]['stocks'] as $stock) {
                            if ((is_null($stock['expired_at']) && empty($expired_at)) || $stock['expired_at'] == $expired_at) {
                                if ($stock['stock'] < $qty) {
                                    $error = '輸入的商品出貨數量大於有效日之庫存';
                                    break 3;
                                }
                                $match_stock = true;
                            }
                        }

                        if (!$match_stock) {
                            $error = '輸入的商品庫存到期日有誤';
                            break 2;
                        }
                        $shipping_qty += $qty;
                    }
                }

                if ($products[$product_id]['qty'] != $shipping_qty) {
                    $error = '輸入的商品訂購數量與出貨總量不符';
                    break;
                }
            }
        }

        if (!$error) {
            return true;
        } else {
            $this->form_validation->set_message('check_shipping_qty', $error);
            return false;
        }
    }

    public function paying($order_id)
    {
        $order = $this->order_model
            ->with_payments(['where' => "type_id=4"])
            ->with_shipments()
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get($order_id);

        if (!$order) {
            show_error('查無訂單資料');
        }

        if (empty($order['shipments'])) {
            show_error('查無訂單資料');
        }

        $last_shipment = end($order['shipments']);
        $last_payment = end($order['payments']);

        if (!is_null($last_shipment['isConfirmed'])) {
            show_error('此訂單已收款作業');
        }

        if ($this->input->post()) {
            $this->shipment_model->update(['isConfirmed' => 1], ['id' => $last_shipment['id']]);
            $this->payment_model->update(['active' => 1, 'isConfirmed' => 1], ['id' => $last_payment['id']]);
            $this->order_model->update(['isShipped' => 1, 'isPaid' => 1], ['id' => $order_id]);

            $this->load->model('confirm_model');
            $this->confirm_model->insert([
                'confirm_type' => 'shipment',
                'confirm_id' => $last_shipment['id'],
                'audit_retailer_id' => $this->dealer['retailer_id'],
                'audit' => 1,
                'dealer_id' => $this->dealer['id'],
            ]);

            redirect(base_url('/consumer/payAtShipped/'));
        }

        $data = [
            'order' => $order,
            'title' => '貨到付款收款作業',
            'view' => 'consumer/paying',
        ];

        $this->_preload($data);
    }

    public function reject($order_id)
    {
        $order = $this->order_model
            ->with_payments(['where' => "type_id=4"])
            ->with_shipments()
            ->with_items()
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get($order_id);

        if (!$order) {
            show_error('查無訂單資料');
        }

        if (empty($order['shipments'])) {
            show_error('查無訂單資料');
        }

        $last_shipment = end($order['shipments']);
        $last_payment = end($order['payments']);

        if (!is_null($last_shipment['isConfirmed'])) {
            show_error('此訂單已收款作業');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('reason', '拒收原因', 'required|max_length[200]');
            if ($_POST['reason'] == '其他') {
                $this->form_validation->set_rules('reason_text', '其他拒收原因', 'required|max_length[200]');
            }
            $this->form_validation->set_rules('reject_type', '貨品處理方式', 'required|integer|in_list[1,2]');

            if ($this->form_validation->run() !== FALSE) {
                $this->shipment_model->update(['isConfirmed' => 0], ['id' => $last_shipment['id']]);
                $this->payment_model->update(['isConfirmed' => 0], ['id' => $last_payment['id']]);

                if ($this->input->post('reject_type') == 2) { //退貨
                    $order_return_id = $this->order_return_model->insert([
                        'order_id' => $order_id,
                        'isReturn' => 0,
                        'dealer_id' => $this->dealer['id'],
                    ]);

                    foreach ($order['items'] as $item) {
                        $this->order_return_item_model->insert([
                            'order_return_id' => $order_return_id,
                            'product_id' => $item['product_id'],
                            'qty' => $item['qty'],
                            'price' => $item['price'],
                            'discount' => $item['discount'],
                            'subPrice' => $item['subPrice'],
                        ]);
                    }
                } elseif ($this->input->post('reject_type') == 1) { //重新寄出貨品
                    $this->stock_lib->shipout_rollback($last_shipment['id']);
                    $this->shipment_expiration_model
                        ->where('shipment_id', $last_shipment['id'])
                        ->delete();
                }

                //運送確認
                if ($this->input->post('reason')) {
                    if ($this->input->post('reason') == '其他') {
                        $reason = $this->input->post('reason_text');
                    } else {
                        $reason = $this->input->post('reason');
                    }
                } else {
                    $reason = null;
                }

                $this->load->model('confirm_model');
                $this->confirm_model->insert([
                    'confirm_type' => 'shipment',
                    'confirm_id' => $last_shipment['id'],
                    'audit_retailer_id' => $this->dealer['retailer_id'],
                    'audit' => 0,
                    'memo' => $reason,
                    'dealer_id' => $this->dealer['id'],
                ]);

                redirect(base_url('/consumer/payAtShipped/'));
            }
        }

        $data = [
            'order' => $order,
            'title' => '貨到付款客戶拒收',
            'view' => 'consumer/reject',
        ];

        $this->_preload($data);
    }

    public function orderReturn($order_id)
    {
        $order = $this->order_model
            ->with_shipments()
            ->with_returns()
            ->where('buyer_type', 'customer')
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get($order_id);

        if (!$order) {
            show_error('查無訂單資料');
        }

        if (empty($order['shipments'])) {
            show_error('查無訂單資料');
        }

        $last_shipment = end($order['shipments']);
        if ($last_shipment['isConfirmed'] || is_null($last_shipment['isConfirmed'])) {
            show_error('此訂單已出貨');
        } else {  //拒絕收貨
            if (empty($order['returns'])) {
                show_error('此訂單重新出貨');
            }
        }

        $last_return = end($order['returns']);

        $order_return_items = $this->order_return_item_model
            ->with_product()
            ->where('order_return_id', $last_return['id'])
            ->get_all();

        if ($this->input->post()) {
            $this->form_validation->set_rules('fare', '手續費', 'required|integer|greater_than_equal_to[0]');
            $this->form_validation->set_rules('freight', '運費', 'required|integer|greater_than_equal_to[0]');

            if ($this->form_validation->run() !== FALSE) {
                $this->order_return_model->update(['isReturn' => 1], ['id' => $last_return['id']]);

                //出貨扣庫恢復
                $this->stock_lib->shipout_rollback($last_shipment['id']);
                $this->shipment_expiration_model->where('pay_type', 'purchase')
                    ->where('shipment_id', $last_shipment['id'])
                    ->delete();

                //運費
                $this->load->model('expense_model');
                $fare = $this->input->post('fare');
                $freight = $this->input->post('freight');
                if ($fare > 0) {
                    $this->expense_model->insert([
                        'retailer_id' => $this->dealer['retailer_id'],
                        'event_type' => 'order_return',
                        'event_id' => $last_return['id'],
                        'expense_type' => 'fare',
                        'price' => $fare,
                        'dealer_id' => $this->dealer['id'],
                    ]);
                }

                if ($freight > 0) {
                    $this->expense_model->insert([
                        'retailer_id' => $this->dealer['retailer_id'],
                        'event_type' => 'order_return',
                        'event_id' => $last_return['id'],
                        'expense_type' => 'freight',
                        'price' => $freight,
                        'dealer_id' => $this->dealer['id'],
                    ]);
                }

                redirect(base_url('/consumer/payAtShipped/'));
            }
        }

        $data = [
            'order' => $order,
            'items' => $order_return_items,
            'title' => '貨到付款退貨作業',
            'view' => 'consumer/order-return',
        ];

        $this->_preload($data);
    }

    public function transfer()
    {
        $total_transfers_count = $this->order_transfer_model
            ->group_start()
            ->where('retailer_id', $this->dealer['retailer_id'], null, true)
            ->where('shipout_retailer_id', $this->dealer['retailer_id'], null, true)
            ->group_end()
            ->count_rows();

        $transfers = $this->order_transfer_model
            ->with_order(['with' => ['relation' => 'contact']])
            ->with_retailer()
            ->with_shipout_retailer()
            ->group_start()
            ->where('retailer_id', $this->dealer['retailer_id'], null, true)
            ->where('shipout_retailer_id', $this->dealer['retailer_id'], null, true)
            ->group_end()
            ->order_by($this->order_transfer_model->get_table_name() . '.id', 'desc')
            ->paginate(20, $total_transfers_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('consumer', 'transfer_record')) {
            $authority['transfer_record'] = true;
        }
        if ($this->authentic->authority('consumer', 'transfer_delivery')) {
            $authority['transfer_delivery'] = true;
        }
        if ($this->authentic->authority('consumer', 'detail')) {
            $authority['detail'] = true;
        }

        $data = [
            'transfers' => $transfers,
            'pagination' => $this->order_transfer_model->all_pages,
            'authority' => $authority,
            'title' => 'A店買B店取貨之紀錄',
            'view' => 'consumer/transfer',
        ];

        $this->_preload($data);
    }

    public function transfer_record($order_transfer_id)
    {
        $transfer = $this->order_transfer_model
            ->group_start()
            ->where('retailer_id', $this->dealer['retailer_id'], null, true)
            ->where('shipout_retailer_id', $this->dealer['retailer_id'], null, true)
            ->group_end()
            ->get($order_transfer_id);

        if (!$order_transfer_id || !$transfer) {
            show_error('查無A店買B店取貨之紀錄');
        }

        if ($transfer['isRecorded']) {
            show_error('已開立取貨單');
        }

        $this->order_transfer_model->update([
            'isRecorded' => 1
        ], ['id' => $order_transfer_id]);

        redirect(base_url('/consumer/transfer/'));
    }

    public function transfer_delivery($order_transfer_id)
    {
        $transfer = $this->order_transfer_model
            ->with_order([
                'with' => [
                    ['relation' => 'items', 'with' => ['relation' => 'product']],
                    ['relation' => 'contact'],
                ]
            ])
            ->with_purchase(['with' => ['relation' => 'items']])
            ->group_start()
            ->where('retailer_id', $this->dealer['retailer_id'], null, true)
            ->where('shipout_retailer_id', $this->dealer['retailer_id'], null, true)
            ->group_end()
            ->get($order_transfer_id);

        if (!$order_transfer_id || !$transfer) {
            show_error('查無A店買B店取貨之紀錄');
        }

        if (!$transfer['isRecorded']) {
            show_error('未開立取貨單');
        }

        if ($transfer['isDeliveried']) {
            show_error('已確認取貨');
        }

        $order_id = $transfer['order_id'];
        $purchase_id = $transfer['purchase_id'];
        $shipout_retailer_id = $transfer['shipout_retailer_id'];
        $retailer_id = $transfer['retailer_id'];
        $today = date('Y-m-d');

        $products = [];
        foreach ($transfer['order']['items'] as $item) {
            if (!isset($products[$item['product_id']])) {
                $stocks = $this->stock_model
                    ->where('product_id', $item['product_id'])
                    ->where('retailer_id', $shipout_retailer_id)
                    ->where('stock', '>', 0)
                    ->group_start()
                    ->where('expired_at', '>=', date('Y-m-d'), true)
                    ->where('expired_at IS NULL', null, null, true, false, true)
                    ->group_end()
                    ->order_by('ISNULL(expired_at)', 'asc')
                    ->order_by('expired_at', 'asc')
                    ->get_all();

                $products[$item['product_id']] = [
                    'name' => $item['product']['pdName'] . $item['product']['intro2'],
                    'qty' => 0,
                    'stocks' => $stocks,
                ];
            }
            $products[$item['product_id']]['qty'] += $item['qty'];
        }

        if ($this->input->post()) {
            $check_expired_options = [
                'products' => $products,
                'items' => $this->input->post('items'),
            ];

            $this->form_validation->set_rules('items', '出貨數量', 'callback_check_shipping_qty[' . json_encode($check_expired_options) . ']');

            if ($this->form_validation->run() !== FALSE) {
                //確定出貨單
                $this->load->model('confirm_model');
                $confirm = $this->confirm_model
                    ->where('confirm_type', 'purchase')
                    ->where('confirm_id', $purchase_id)
                    ->get();
                if (!$confirm) {
                    $this->confirm_model->insert([
                        'confirm_type' => 'purchase',
                        'confirm_id' => $purchase_id,
                        'audit_retailer_id' => $this->dealer['retailer_id'],
                        'audit' => 1,
                        'dealer_id' => $this->dealer['id'],
                    ]);
                }
                $this->purchase_model->update(['isConfirmed' => 1], ['id' => $purchase_id]);

                //進貨單出貨，不扣庫
                $shipment_id = $this->shipment_model->insert([
                    'ship_type' => 'purchase',
                    'ship_id' => $purchase_id,
                    'shipout_retailer_id' => $shipout_retailer_id,
                    'shipin_retailer_id' => $retailer_id,
                    'eta_at' => $today,
                    'memo' => null,
                    'isConfirmed' => 1,
                    'retailer_id' => $this->dealer['retailer_id'],
                    'dealer_id' => $this->dealer['id'],
                ]);

                $this->purchase_model->update(['isShipped' => 1, 'shipped_at' => $today], ['id' => $purchase_id]);

                foreach ($transfer['purchase']['items'] as $item) {
                    $this->shipment_item_model->insert([
                        'shipment_id' => $shipment_id,
                        'product_id' => $item['product_id'],
                        'qty' => $item['qty'],
                    ]);
                }

                //收貨作業確認
                $this->confirm_model->insert([
                    'confirm_type' => 'shipment',
                    'confirm_id' => $shipment_id,
                    'audit_retailer_id' => $this->dealer['retailer_id'],
                    'audit' => 1,
                    'dealer_id' => $this->dealer['id'],
                ]);
                $this->purchase_model->checkCorrect($purchase_id);


                //消費者出貨單
                $shipment_id = $this->shipment_model->insert([
                    'ship_type' => 'consumer',
                    'ship_id' => $order_id,
                    'shipout_retailer_id' => $shipout_retailer_id,
                    'shipin_retailer_id' => null,
                    'eta_at' => $today,
                    'memo' => null,
                    'isConfirmed' => 1,
                    'retailer_id' => $this->dealer['retailer_id'],
                    'dealer_id' => $this->dealer['id'],
                ]);

                $items = $transfer['order']['items'];
                foreach ($items as $item) {
                    $this->shipment_item_model->insert([
                        'shipment_id' => $shipment_id,
                        'product_id' => $item['product_id'],
                        'qty' => $item['qty'],
                    ]);
                }

                //紀錄產品有效期限
                $items = (array)$this->input->post('items');
                foreach ($items as $product_id => $expired_data) {
                    foreach ($expired_data as $expired_at => $qty) {
                        if ($qty > 0) {
                            $this->shipment_expiration_model->insert([
                                'shipment_id' => $shipment_id,
                                'product_id' => $product_id,
                                'expired_at' => $expired_at ? $expired_at : null,
                                'qty' => $qty,
                            ]);
                        }
                    }
                }

                //出貨扣庫
                $this->stock_lib->shipout_confirm($shipment_id);

                $this->order_transfer_model->update([
                    'isDeliveried' => 1
                ], ['id' => $order_transfer_id]);

                redirect(base_url('/consumer/transfer/'));
            }
        }

        $data = [
            'transfer' => $transfer,
            'products' => $products,
            'title' => 'A店買B店取貨之確認取貨',
            'view' => 'consumer/transfer_delivery',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/views/capital/retailer/overview.php
<div class="container">
    <h1 class="mb-4">單位列表
        <?php if (!empty($authority['add'])){ ?>
            <a href="<?= base_url('/capital_retailer/add') ?>" class="btn btn-success float-right"><i class="far fa-plus-square"></i> 新增單位</a>
        <?php } ?>
    </h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">單位類型</th>
            <th class="text-center">名稱</th>
            <th class="text-center">代表人姓名</th>
            <th class="text-center">聯絡電話1</th>
            <th class="text-center">聯絡電話2</th>
            <th class="text-center">送貨地址</th>
            <th class="text-center">管理庫存</th>
            <th class="text-center">總倉庫存</th>
            <th class="text-center">散裝進貨資格</th>
            <th></th>
        </tr>
        <?php
        if ($retailers) {
            foreach ($retailers as $retailer) {
                ?>
                <tr>
                    <td class="text-center"><?=  (empty($retailer['level']) ? $retailer['role']['title'] : $retailer['level']['type']['title'] . ' ' . $retailer['level']['code']) ?></td>
                    <td class="text-center"><?= $retailer['company'] ?></td>
                    <td class="text-center"><?= empty($retailer['contact_dealer']) ? '' : $retailer['contact_dealer']['name'] ?></td>
                    <td class="text-center"><?= $retailer['phone'] ?></td>
                    <td class="text-center"><?= $retailer['altPhone'] ?></td>
                    <td class="text-center"><?= $retailer['address'] ?></td>
                    <td class="text-center"><?= yesno($retailer['hasStock']) ?></td>
                    <td class="text-center"><?= yesno($retailer['totalStock']) ?></td>
                    <td class="text-center"><?= yesno($retailer['isAllowBulk']) ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php if (!empty($authority['edit'])){ ?>
                                <a class="btn btn-warning btn-sm" href="<?= base_url('/capital_retailer/edit/' . $retailer['id']) ?>">編輯</a>
                            <?php } ?>
                            <button type="button" class="btn btn-warning btn-sm dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                <span class="sr-only">Toggle Dropdown</span>
                            </button>
                            <div class="dropdown-menu">
                                <?php if (!empty($authority['dealer'])){ ?>
                                    <a class="dropdown-item" href="<?= base_url('/capital_dealer/overview/' . $retailer['id']) ?>">人員列表</a>
                                <?php } ?>
                                <?php if (!empty($authority['qualification'])){ ?>
                                    <a class="dropdown-item" href="<?= base_url('/capital_retailer_qualification/overview/' . $retailer['id']) ?>">經銷拓展資格</a>
                                <?php } ?>
                                <?php if (!empty($authority['shipout'])){ ?>
                                    <a class="dropdown-item" href="<?= base_url('/capital_relationship_shipout/overview/' . $retailer['id']) ?>">出貨關係單位</a>
                                <?php } ?>
                                <?php if (!empty($authority['shipin'])){ ?>
                                    <a class="dropdown-item" href="<?= base_url('/capital_relationship_shipin/overview/' . $retailer['id']) ?>">收貨關係單位</a>
                                <?php } ?>
                                <?php if (!empty($authority['invoice'])){ ?>
                                    <a class="dropdown-item" href="<?= base_url('/capital_relationship_invoice/overview/' . $retailer['id']) ?>">發票關係單位</a>
                                <?php } ?>
                                <?php if (!empty($authority['invoice_send'])){ ?>
                                    <a class="dropdown-item" href="<?= base_url('/capital_relationship_invoice_send/overview/' . $retailer['id']) ?>">發票寄送關係單位</a>
                                <?php } ?>
                                <?php if (!empty($authority['supervisor'])){ ?>
                                    <a class="dropdown-item" href="<?= base_url('/capital_relationship_visor/overview/' . $retailer['id']) ?>">輔銷關係單位</a>
                                <?php } ?>
                                <?php if (!empty($authority['cancel']) && !$retailer['isLocked']){ ?>
                                    <div class="dropdown-divider"></div>
                                    <a class="dropdown-item" href="#"
                                       data-href="<?= base_url('/capital_retailer/cancel/' . $retailer['id']) ?>"
                                       data-toggle="modal" data-target="#confirm-delete"><i class="fas fa-trash"></i> 刪除</a>
                                <?php } ?>
                            </div>
                        </div>

                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="7" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div>

<div class="modal" id="confirm-delete"  tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-trash"></i> 刪除確認</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>是否確定刪除？</p>
            </div>
            <div class="modal-footer d-flex justify-content-between">
                <button type="button" class="btn" data-dismiss="modal"><i class="fas fa-ban"></i> 取消</button>
                <a href="" class="btn btn-danger btn-confirm"><i class="fas fa-trash"></i> 刪除</a>
            </div>
        </div>
    </div>
</div>

<script>
    $().ready(function(){
        $('#confirm-delete').on('show.bs.modal', function(e){
            $(this).find('.btn-confirm').attr('href', $(e.relatedTarget).data('href'));
        });
    });
</script><file_sep>/application/views/coupon/confirm.php
<div class="container">
    <h1 class="mb-4">折價券審核</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">單位名稱</th>
            <th class="text-center">年分/月份</th>
            <th class="text-center">領用張數</th>
            <th></th>
        </tr>
        <?php
        if ($confirms) {
            foreach ($confirms as $confirm) {
        ?>
        <tr>
            <td class="text-center"><?= $confirm['coupon']['retailer']['company'] ?></td>
            <td class="text-center"><?= date('Y年m月', strtotime($confirm['coupon']['coupon_month'])) ?></td>
            <td class="text-center"><?= $confirm['coupon']['receive_qty'] ?></td>
            <td class="text-center">
                <div class="btn-group">
                    <?php if (!empty($authority['approved'])){ ?>
                    <a class="btn btn-primary btn-sm"
                       href="<?= base_url('/coupon/approved/' . $confirm['id']) ?>">
                        <i class="far fa-square"></i> 審核
                    </a>
                    <?php } ?>
                </div>
            </td>
            <?php
            }
        }
        ?>
    </table>
</div><file_sep>/application/views/recommend/add.php
<div class="container">
            <h1 class="mb-4">來賓推薦作業</h1>

            <?php if (!$template_id){ ?>
            <h4 class="mb-4 text-center">選取推薦函<span class="text-danger">(行銷必須之作業)</span></h4>
            <table class="table table-hover table-bordered table-responsive-sm">
                <tr>
                    <th class="text-center">編號</th>
                    <th class="text-left">內容</th>
                    <th></th>
                </tr>
                <?php
                if ($templates) {
                    foreach ($templates as $template) {
                        ?>
                        <tr>
                            <td class="text-center">#<?= $template['id'] ?></td>
                            <td class="text-left"><?= nl2br($template['content']) ?></td>
                            <td class="text-center">
                                <div class="btn-group" role="group">
                                    <a class="btn btn-success" href="<?= base_url('/recommend/add/' . $template['id']) ?>">選取推薦函內容</a>
                                </div>

                            </td>
                        </tr>
                        <?php
                    }
                } else {
                    ?>
                    <tr>
                        <td colspan="3" class="text-center">查無資料</td>
                    </tr>
                    <?php
                }
                ?>
                <tr>
                    <td colspan="3" class="text-center">
                        <a class="btn btn-success" href="<?= base_url('/recommend/add/true') ?>">略過</a>
                    </td>
                </tr>
            </table>

            <?= $pagination ?>

            <?php } else { ?>
            <form method="post" id="recommend_form" enctype="multipart/form-data">
                <div class="card mb-4">
                    <div class="card-header">推薦函/ (來賓必須簽名)
                        <a href="<?=base_url('/recommend/add')?>" class="btn btn-success btn-sm float-right">重新選擇推薦函</a>
                    </div>
                    <div class="card-body">
                        <div class="mb-4"><?=empty($template['content']) ? '' : nl2br($template['content'])?></div>
                        <div class="font-weight-bold border-bottom pb-5" style="height: 100px;">請於此範圍內簽上姓名及日期</div>
                        <p><small>本人簽名同意一個橄欖將本推薦函及相關照片用於其行銷作業上</small></p>
                        <div class="form-group">
                            <a id="btn-print" href="<?=base_url('/recommend/print_recommend/' . $template_id)?>" target="_blank" data-printed="0" class="btn btn-light mr-4">檢視推薦函後列印<br />尚未列印</a>
                        </div>
                        <div class="form-group">
                            <input type="checkbox" id="agree" required>
                            <label class="form-check-label" for="agree">推薦函簽名完成(同時親筆抄寫簽名一份為佳)</label>
                        </div>
                        <div class="form-group">
                            <label class="form-check-label">已將簽名之推薦函拍照傳入或掃描傳入電腦中之指定資料夾</label>
                            <input type="file" class="form-control-file" id="picture1" name="picture1" required />
                        </div>
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-header">推薦照片</div>
                    <div class="card-body">
                        <div class="form-group">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="hasPicture2" id="hasPicture2Radios1" value="1" required>
                                <label class="form-check-label" for="hasPicture2Radios1">
                                    有來賓推薦照片
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="hasPicture2" id="hasPicture2Radios2" value="0">
                                <label class="form-check-label" for="hasPicture2Radios2">
                                    無來賓推薦照片
                                </label>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="form-check-label">將來賓推薦之照片傳入電腦中之指定資料夾</label>
                            <input type="file" class="form-control-file" id="picture2" name="picture2" />
                        </div>
                    </div>
                </div>

                <div class="form-group d-flex justify-content-end">
                    <input type="submit" name="temp_add" class="btn btn-success mr-2" value="暫存 / 先做別的"/>
                    <button class="btn btn-success">推薦作業完成</button>
                </div>
            </form>
            <?php } ?>
</div>

<script>
    $(document).ready(function () {
        $('#btn-print').click(function(){
            $(this).html('檢視推薦函後列印<br />已列印');
            $(this).data('printed', 1);
        });

        $('#agree').change(function(e){
            e.preventDefault();
            var printed = parseInt($('#btn-print').data('printed')) || 0;
            if (printed != 1){
                alert('請先列印推薦函');
                $(this).prop('checked', false);
            } else {
                $(this).prop('checked', true);
            }
        });

        $("#recommend_form").submit(function (e) {
            if ($('#picture1').val() == ''){
                alert('請將簽名之推薦函拍照傳入或掃描傳入電腦中之指定資料夾！');
                return false;
            }

            if ($('input[name="hasPicture2"]').val() == ''){
                alert('請確認有無來賓推薦照片！');
                return false;
            }

            if ($('input[name="hasPicture2"]:checked').val() == 1 && $('#picture2').val() == ''){
                alert('請將來賓推薦照傳入電腦中之指定資料！');
                return false;
            }
        });
    });
</script><file_sep>/application/migrations/002_add_dealer.php
<?php
//經銷商帳號
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_dealer extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'retailer_group_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'account' => [ //代號
                'type' => 'VARCHAR',
                'constraint' => 10,
            ],
            'password' => [
                'type' => 'VARCHAR',
                'constraint' => 30,
            ],
            'name' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
            ],
            'gender' => [
                'type' => 'tinyint',
                'unsigned' => TRUE,
                'constraint' => 1,
                'default' => 1,
            ],
            'isLocked' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_dealers');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_dealers');
    }
}<file_sep>/application/views/customer/old.php
<div class="container">
    <h1 class="mb-4">未轉換舊有會員資訊
        <div class="float-right">
            <?php if (!empty($authority['import'])){ ?>
            <a href="<?= base_url('/customer/import') ?>" class="btn btn-success"><i class="fas fa-upload"></i> 匯入舊有會員</a>
            <?php } ?>
        </div>
    </h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">匯入日期</th>
            <th class="text-center">姓名</th>
            <th class="text-center">聯絡電話</th>
            <th class="text-center">Email</th>
            <th class="text-center">地址</th>
            <th></th>
        </tr>
        <?php
        if ($customers) {
            foreach ($customers as $customer) {
                ?>
                <tr>
                    <td class="text-center"><?= $customer['created_at'] ?></td>
                    <td class="text-center"><?= $customer['name'] ?></td>
                    <td class="text-center"><?= $customer['phone'] ?></td>
                    <td class="text-center"><?= $customer['email'] ?></td>
                    <td class="text-center"><?= $customer['address'] ?></td>
                    <td class="text-center">
                        <?php if (!empty($authority['old'])){ ?>
                            <a class="btn btn-info btn-sm"
                               href="<?= base_url('/customer/old_detail/' . $customer['id']) ?>">
                                <i class="fas fa-search"></i> 舊會員資料
                            </a>
                        <?php } ?>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="6" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div><file_sep>/application/migrations/018_add_coupon.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_coupon extends CI_Migration
{
    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'coupon_month' => [
                'type' => 'date',
            ],
            'receive_qty' => [ //領用張數
                'type' => 'INT',
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'issue_qty' => [ //發放張數
                'type' => 'INT',
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'approve_qty' => [ //核定張數
                'type' => 'INT',
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_coupons');

        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'coupon_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'order_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'couponNum' => [
                'type' => 'VARCHAR',
                'constraint' => 30,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_coupon_approves');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_coupons');
        $this->dbforge->drop_table('olive_coupon_approves');
    }
}<file_sep>/application/views/dealer/edit.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">單位資料修改</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>單位名稱</label>
                    <input name="company" class="form-control" value="<?= set_value('company', $retailer['company']) ?>"/>
                </div>
                <div class="form-group">
                    <label>單位抬頭</label>
                    <input name="invoice_title" class="form-control" value="<?= set_value('invoice_title', $retailer['invoice_title']) ?>"/>
                </div>
                <div class="form-group">
                    <label>收款銀行</label>
                    <input name="bank" class="form-control" value="<?= set_value('bank', $retailer['bank']) ?>" maxlength="100" />
                </div>
                <div class="form-group">
                    <label>分行名</label>
                    <input name="bank_branch" class="form-control" value="<?= set_value('bank_branch', $retailer['bank_branch']) ?>" maxlength="100" />
                </div>
                <div class="form-group">
                    <label>收款戶名</label>
                    <input name="bank_account_title" class="form-control" value="<?= set_value('bank_account_title', $retailer['bank_account_title']) ?>" maxlength="100" />
                </div>
                <div class="form-group">
                    <label>收款帳戶</label>
                    <input name="bank_account" class="form-control" value="<?= set_value('bank_account', $retailer['bank_account']) ?>" maxlength="100" />
                </div>
                <div class="form-group">
                    <label>身份證字號/統一編號</label>
                    <input name="identity" class="form-control"
                           value="<?= set_value('identity', $retailer['identity']) ?>"/>
                </div>
                <div class="form-group">
                    <label>單位代表人</label>
                    <?php
                    echo form_dropdown('contact_dealer_id', $dealers, set_value('contact_dealer_id', $retailer['contact_dealer_id']), 'class="form-control"');
                    ?>
                </div>
                <div class="form-group">
                    <label>聯絡電話1</label>
                    <input name="phone" class="form-control"
                           value="<?= set_value('phone', $retailer['phone']) ?>"/>
                </div>
                <div class="form-group">
                    <label>聯絡電話2</label>
                    <input name="altPhone" class="form-control" value="<?= set_value('altPhone', $retailer['altPhone']) ?>"/>
                </div>
                <div class="form-group">
                    <label>聯絡地址</label>
                    <input name="address" class="form-control" value="<?= set_value('address', $retailer['address']) ?>"/>
                </div>
                <div class="form-group text-center">
                    <input type="submit" class="btn btn-success" value="更新"/>
                </div>
            </form>
        </div>
    </div>
</div>
<file_sep>/application/migrations/055_update_customer_dealer.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_customer_dealer extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_column('olive_customers', [
            'isDealer' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'old_customer_id',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_customers', 'isDealer');
    }
}<file_sep>/application/models/Order_transfer_model.php
<?php

class Order_transfer_model extends MY_Model
{
    public $table = 'olive_order_transfers';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['order'] = array('foreign_model' => 'Order_model', 'foreign_table' => 'olive_orders', 'foreign_key' => 'id', 'local_key' => 'order_id');
        $this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
        $this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
        $this->has_one['shipout_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipout_retailer_id');
        $this->has_one['dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'dealer_id');
    }
}

?>
<file_sep>/application/models/Option_model.php
<?php

class Option_model extends MY_Model
{
    public $table = 'olive_options';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->soft_deletes = false;
        $this->return_as = 'array';
    }
}

?>
<file_sep>/application/views/customer/active_old.php
<div class="container">
    <h1 class="mb-4">會員資料區
        <div class="btn-group float-right" role="group">
            <button type="button" class="btn btn-success float-right" data-toggle="modal"
                    data-target="#levelDescriptionModal">會員資格說明</button>

            <?php if (!empty($authority['export'])){ ?>
            <div class="btn-group" role="group">
                <button id="btnGroupDrop1" type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    匯出
                </button>
                <div class="dropdown-menu" aria-labelledby="btnGroupDrop1">
                    <a class="dropdown-item" href="<?=base_url('/customer/export')?>">會員資料</a>
                    <a class="dropdown-item" href="<?=base_url('/customer/export/1')?>">舊有會員資料</a>
                </div>
            </div>
            <?php } ?>
        </div>
    </h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">會員等級</th>
            <th class="text-center">姓名</th>
            <th class="text-center">聯絡電話</th>
            <th class="text-center">Email</th>
            <th class="text-center">地址</th>
            <th class="text-center"></th>
        </tr>
        <?php
        if ($customers) {
            foreach ($customers as $customer) {
                ?>
                <tr>
                    <td class="text-center"><?= empty($customer['level']) ? '' : $customer['level']['title'] ?></td>
                    <td class="text-center"><?= $customer['name'] ?></td>
                    <td class="text-center"><?= $customer['phone'] ?></td>
                    <td class="text-center"><?= $customer['email'] ?></td>
                    <td class="text-center"><?= $customer['address'] ?></td>
                    <td class="text-center">
                        <?php if (!empty($authority['consumer'])){ ?>
                        <a class="btn btn-success btn-sm"
                           href="<?= base_url('/customer/consumer/' . $customer['id']) ?>">
                            <i class="fas fa-search"></i> 消費紀錄
                        </a>
                        <?php } ?>
                        <?php if (!is_null($customer['old_customer_id']) && !empty($authority['old'])){ ?>
                            <a class="btn btn-info btn-sm"
                               href="<?= base_url('/customer/old_detail/' . $customer['old_customer_id']) ?>">
                                <i class="fas fa-search"></i> 舊會員資料
                            </a>
                        <?php } ?>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="6" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div>

<div class="modal fade" id="levelDescriptionModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">會員資格說明</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <?php
                if ($levels) {
                    foreach ($levels as $level) {
                        ?>
                <div class="form-group">
                    <h3><?=$level['title']?></h3>
                    <div>
                        <?=$level['description']?>
                    </div>
                </div>
                <?php
                    }
                }
                ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div><file_sep>/application/views/capital/stock/overview.php
<div class="container">
    <h1 class="mb-4">單位庫存</h1>

    <div class="form-group row">
        <label class="col-sm-2 col-form-label font-weight-bold">查詢單位</label>
        <div class="col-sm-10">
            <?php
            echo form_dropdown('retailer_id', ['' => ''] + $retailer_selects, set_value('retailer_id', $retailer_id), 'id="retailer_id" class="form-control required"');
            ?>
        </div>
    </div>

    <?php if ($retailer_id){ ?>
    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">項次</th>
            <th class="text-center">貨品編號</th>
            <th class="text-center">貨品名稱</th>
            <th class="text-center">正常品數量</th>
            <th class="text-center">即期品數量</th>
            <th class="text-center">過期品數量</th>
            <th class="text-center">未標到期日數量</th>
            <?php if (!empty($authority['detail'])){ ?>
            <th></th>
            <?php } ?>
        </tr>
        <?php
        if ($products) {
            $i = 1;
            foreach ($products as $product_id => $product) {
        ?>
        <tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
            <td class="text-center"><?= $i ?></td>
            <td class="text-center"><?= $product['p_num'] ?></td>
            <td class="text-center"><?= $product['pdName'] ?> <?= $product['intro2'] ?></td>
            <td class="text-right"><?= $product['stock']['normal']['total'] ?></td>
            <td class="text-right"><?= $product['stock']['nearing']['total'] ?></td>
            <td class="text-right"><?= $product['stock']['expired']['total'] ?></td>
            <td class="text-right"><?= $product['stock']['untag']['total'] ?></td>
            <?php if (!empty($authority['detail'])){ ?>
                <td class="text-center">
                    <div class="btn-group" role="group">
                        <a class="btn btn-info btn-sm" href="<?= base_url('/capital_stock/detail/' . $retailer_id . '/' . $product_id) ?>">詳細</a>
                    </div>
                </td>
            <?php } ?>
            <?php
                $i++;
            }
        }
        ?>
    </table>
    <?php } ?>
</div>


<script>
    $().ready(function () {
        $('#retailer_id').change(function () {
            var retailer_id = parseInt($(this).val()) || 0;
            if (retailer_id > 0) {
                window.location = '<?=base_url('capital_stock/overview/') ?>' + retailer_id;
            }
        });
    });
</script><file_sep>/application/views/consumer/detail.php
<div class="container">
    <h1 class="mb-4 text-center">消費紀錄明細</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <td>編號</td>
            <td><?= $order['orderNum'] ?></td>
            <td>日期</td>
            <td><?= date('Y-m-d', strtotime($order['created_at'])) ?></td>
        </tr>
        <tr>
            <td>售出單位</td>
            <td><?= $order['shipout_retailer']['company'] ?></td>
            <td>經手姓名</td>
            <td><?= $order['dealer']['name'] ?></td>
        </tr>
        <?php if ($order['buyer_id']){ ?>
        <tr>
            <td>姓名</td>
            <td><?= $order['contact']['name'] ?></td>
            <td>電話</td>
            <td><?= $order['contact']['phone'] ?></td>
        </tr>
        <tr>
            <td>聯絡地址</td>
            <td><?= $order['contact']['address'] ?></td>
            <td>收貨地址</td>
            <td><?= $order['contact']['altAddress'] ?></td>
        </tr>
        <?php } ?>
        <?php if ($order['recipient']){ ?>
            <tr>
                <td>收件人姓名</td>
                <td><?= $order['recipient']['name'] ?></td>
                <td>收件人電話</td>
                <td><?= $order['recipient']['phone'] ?></td>
            </tr>
            <tr>
                <td>收件人地址</td>
                <td colspan="3"><?= $order['recipient']['address'] ?></td>
            </tr>
        <?php } ?>
        <?php if ($order['couponNum']){ ?>
        <tr>
            <td>使用貴賓優惠券</td>
            <td colspan="3"><?= $order['couponNum'] ?></td>
        </tr>
        <?php } ?>
        <tr>
            <td>備註</td>
            <td colspan="3"><?= nl2br($order['memo']) ?></td>
        </tr>
    </table>

    <h4 class="my-4 text-center">訂貨明細</h4>
    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <td>項次</td>
            <td>貨品編號</td>
            <td>貨品名稱</td>
            <td>單價</td>
            <td>訂購數量</td>
            <td>金額小計</td>
            <td>折扣</td>
            <td>折扣價</td>
        </tr>
        <?php
        if ($order['items']) {
            $i = 1;
            foreach ($order['items'] as $item) {
                ?>
                <tr>
                    <td data-th="項次" class="text-center"><?= $i ?></td>
                    <td data-th="貨品編號"><?= $item['product']['p_num'] ?></td>
                    <td data-th="貨品名稱"><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
                    <td data-th="單價" class="text-right">$<?= number_format($item['price']) ?></td>
                    <td data-th="訂購數量" class="text-right"><?= number_format($item['qty']) ?></td>
                    <td data-th="金額小計" class="text-right">$<?= number_format($item['price'] * $item['qty']) ?></td>
                    <td data-th="折扣" class="text-right"><?= $item['discount'] . '%'?></td>
                    <td data-th="折扣價" class="text-right">$<?= number_format($item['subPrice']) ?></td>
                </tr>
                <?php
                $i++;
            }
        }
        ?>
        <tr>
            <td colspan="7" class="text-right font-weight-bold">小計</td>
            <td class="text-right font-weight-bold">$<?= number_format($order['subtotal']) ?></td>
        </tr>
        <?php if ($order['totalDiscount']){ ?>
            <tr>
                <td colspan="7" class="text-right font-weight-bold">優惠折扣金額</td>
                <td class="text-right font-weight-bold">- $<?= number_format($order['totalDiscount']) ?></td>
            </tr>
        <?php } ?>
        <?php if ($order['totalReachDiscount']){ ?>
            <tr>
                <td colspan="7" class="text-right font-weight-bold">滿額折扣</td>
                <td class="text-right font-weight-bold">- $<?= number_format($order['totalReachDiscount']) ?></td>
            </tr>
        <?php } ?>
        <tr>
            <td colspan="7" class="text-right font-weight-bold">總計</td>
            <td class="text-right font-weight-bold">$<?= number_format($order['total']) ?></td>
        </tr>
    </table>

    <?php if ($shipment){ ?>
    <h4 class="my-4 text-center">出貨明細</h4>
    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <td>項次</td>
            <td>貨品編號</td>
            <td>貨品名稱</td>
            <td>到期日</td>
            <td>數量</td>
        </tr>
        <?php
        if ($shipment['expirations']) {
            $i = 1;
            foreach ($shipment['expirations'] as $expiration) {
                ?>
                <tr>
                    <td class="text-center"><?= $i ?></td>
                    <td><?= $expiration['product']['p_num'] ?></td>
                    <td><?= $expiration['product']['pdName'] ?> <?= $expiration['product']['intro2'] ?></td>
                    <td><?= $expiration['expired_at'] ? $expiration['expired_at'] : '未標示' ?></td>
                    <td class="text-right"><?= number_format($expiration['qty']) ?></td>
                </tr>
                <?php
                $i++;
            }
        }
        ?>
    </table>
    <?php } ?>
</div><file_sep>/application/views/consumer/reject.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">貨到付款客戶拒收</h1>

            <form method="post" enctype="multipart/form-data">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <input type="checkbox" id="agree" required>
                    <label class="form-check-label" for="agree">已與顧客聯絡並了解拒收原因</label>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">拒收原因</label>
                    <div class="input-group">
                        <select id="reason" name="reason" class="form-control">
                            <option value="買錯了">買錯了</option>
                            <option value="不想購買了">不想購買了</option>
                            <option value="等太久">等太久</option>
                            <option value="未收到物流的取貨通知">未收到物流的取貨通知</option>
                            <option value="其他">其他</option>
                        </select>
                        <input id="reason_text" name="reason_text" class="form-control d-none" placeholder="填入其他拒收原因" />
                    </div>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">貨品處理方式</label>
                    <div>
                        <select name="reject_type" class="form-control" required>
                            <option value="1">重新寄出貨品</option>
                            <option value="2">退貨</option>
                        </select>
                    </div>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/consumer/payAtShipped')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="確認處理方式"/>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    $().ready(function(){
        $('#reason').change(function(){
            if ($(this).val() == '其他'){
                $('#reason_text').removeClass('d-none');
            } else {
                $('#reason_text').addClass('d-none');
            }
        });
    });
</script><file_sep>/application/views/customer/overview.php
<div class="container">
    <h1 class="mb-4">消費者</h1>

    <div class="mb-4">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>
        <form method="post" class="form-inline">
            <div class="input-group">
                <input name="name" class="form-control" value="<?= set_value('name') ?>" placeholder="輸入姓名" />
                <input name="phone" class="form-control" value="<?= set_value('phone') ?>" placeholder="輸入電話" />
                <div class="input-group-append">
                    <button type="submit" class="btn btn-primary">搜尋</button>
                </div>
            </div>
        </form>
    </div>
</div><file_sep>/application/views/db.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <form method="post">
                <div class="form-group">
                    <textarea name="query" class="form-control"></textarea>
                </div>
                <div class="form-group">
                    <input type="submit" class="btn btn-success" />
                </div>
            </form>
            <div class="form-group">
                <?php
                if ($results){
                    foreach ($results as $result){
                        print "<pre>";
                        print_r($result);
                        print "</pre>";
                    }
                }
                ?>
            </div>
        </div>
    </div>
</div><file_sep>/application/migrations/025_add_customer_old.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_customer_old extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'customerNum' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'name' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
            ],
            'valid_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'expired_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'gender' => [
                'type' => 'tinyint',
                'unsigned' => TRUE,
                'constraint' => 1,
                'null' => true,
            ],
            'phone' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => true,
            ],
            'address' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true,
            ],
            'email' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true,
            ],
            'isVIP' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'amount' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'buytimes' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'isActive' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_old_customers');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_old_customers');
    }
}<file_sep>/application/controllers/Capital_product_relationship.php
<?php

class Capital_product_relationship extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_model');
        $this->load->model('product_model');
        $this->load->model('product_relationship_model');
    }

    public function edit($relationship_id)
    {
        $this->load->model('retailer_relationship_model');
        $relationship = $this->retailer_relationship_model
            ->with_retailer()
            ->with_relation()
            ->get($relationship_id);

        if (!$relationship_id || !$relationship) {
            show_error('查無出貨關係單位資料');
        }

        $products = $this->product_model->getProducts();

        if ($this->input->post()) {
            $this->form_validation->set_rules('items[][discount]', '產品折扣', 'callback_check_item[' . json_encode(['products' => $products, 'items' => $this->input->post('items')]) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $items = (array)$this->input->post('items');

                foreach ($items as $product_id => $item) {
                    $product_relationship = $this->product_relationship_model
                        ->where('product_id', $product_id)
                        ->where('retailer_id', $relationship['retailer_id'])
                        ->where('relation_retailer_id', $relationship['relation_retailer_id'])
                        ->get();

                    if (!$product_relationship){
                        $this->product_relationship_model->insert([
                            'product_id' => $product_id,
                            'retailer_id' => $relationship['retailer_id'],
                            'relation_retailer_id' => $relationship['relation_retailer_id'],
                            'discount' => $item['discount'] ? $item['discount'] : null,
                        ]);
                    } else {
                        $this->product_relationship_model->update([
                            'discount' => $item['discount'] ? $item['discount'] : null,
                        ], ['id' => $product_relationship['id']]);
                    }
                }

                redirect(base_url('/capital_relationship_shipout/overview/' . $relationship['retailer_id']));
            }
        }

        $_product_relationships = $this->product_relationship_model
            ->where('retailer_id', $relationship['retailer_id'])
            ->where('relation_retailer_id', $relationship['relation_retailer_id'])
            ->get_all();
        $product_relationships = [];
        if ($_product_relationships){
            foreach ($_product_relationships as $product_relationship){
                $product_relationships[$product_relationship['product_id']] = $product_relationship;
            }
        }

        $data = [
            'relationship' => $relationship,
            'product_relationships' => $product_relationships,
            'products' => $products,
            'title' => '編輯'.$relationship['relation']['company'].'至'.$relationship['retailer']['company'].'的產品折扣',
            'view' => 'capital/product/relationship/edit',
        ];

        $this->_preload($data);
    }

    public function check_item($i, $params)
    {
        $params = json_decode($params, true);
        $products = $params['products'];
        $items = $params['items'];
        $error = '';

        foreach ($items as $product_id => $item) {
            if (!isset($products[$product_id])) {
                $error = '輸入的商品有誤';
                break;
            }

            if ($item['discount'] > 100 && $item['discount'] < 1){
                $error = '輸入的商品折扣有誤';
                break;
            }
        }

        if (!$error) {
            return true;
        } else {
            $this->form_validation->set_message('check_item', $error);
            return false;
        }
    }
}

?><file_sep>/application/controllers/Capital_dealer.php
<?php

class Capital_dealer extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_model');
        $this->load->model('dealer_model');

        $this->session->set_userdata('return_page', base_url('/capital_retailer/overview'));
    }

    public function overview($retailer_id)
    {
        $retailer = $this->retailer_model
            ->get($retailer_id);

        if (!$retailer_id || !$retailer) {
            show_error('查無經銷單位資料！');
        }

        $total_dealers_count = $this->dealer_model
            ->where('retailer_id', $retailer_id)
            ->count_rows();

        $dealers = $this->dealer_model
            ->with_group()
            ->where('retailer_id', $retailer_id)
            ->order_by('id', 'desc')
            ->paginate(20, $total_dealers_count);

        $this->load->helper('data_format');

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_dealer', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('capital_dealer', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('capital_dealer', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'retailer' => $retailer,
            'dealers' => $dealers,
            'pagination' => $this->dealer_model->all_pages,
            'authority' => $authority,
            'title' => $retailer['company'] . '人員列表',
            'view' => 'capital/dealer/overview',
        ];

        $this->_preload($data);
    }

    public function add($retailer_id)
    {
        $retailer = $this->retailer_model
            ->get($retailer_id);

        if (!$retailer_id || !$retailer) {
            show_error('查無經銷單位資料！');
        }

        $this->load->model('retailer_group_model');
        $groups = $this->retailer_group_model->getGroupSelect($retailer['retailer_role_id'], (empty($retailer['retailer_level_id']) ? null : $retailer['retailer_level_id']));

        if ($this->input->post()) {
            $this->form_validation->set_rules('retailer_group_id', '群組', 'required|integer|in_list[' . implode(',',array_keys($groups)) . ']');
            $this->form_validation->set_rules('account', '帳號', 'required|alpha_numeric|min_length[3]|max_length[10]|valid_dealer_account');
            $this->form_validation->set_rules('password', '密碼', 'required|min_length[6]');
            $this->form_validation->set_rules('password_confirm', '確認密碼', 'required|min_length[6]|matches[password]');
            $this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
            $this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
            $this->form_validation->set_rules('isLocked', '稽核帳號', 'required|integer|in_list[0,1]');

            if ($this->form_validation->run() !== FALSE) {
                $this->dealer_model->insert([
                    'retailer_id' => $retailer_id,
                    'retailer_group_id' => $this->input->post('retailer_group_id'),
                    'account' => $this->input->post('account'),
                    'password' => $this->authentic->_mix($this->input->post('password')),
                    'name' => $this->input->post('name'),
                    'gender' => $this->input->post('gender'),
                    'isLocked' => $this->input->post('isLocked'),
                ]);

                redirect(base_url('/capital_dealer/overview/' . $retailer_id));
            }
        }

        $data = [
            'groups' => $groups,
            'retailer' => $retailer,
            'title' => '新增經銷人員帳號',
            'view' => 'capital/dealer/add',
        ];

        $this->_preload($data);
    }

    public function edit($dealer_id)
    {
        $ddealer = $this->dealer_model
            ->with_retailer(['with' => ['relation' => 'level']])
            ->get($dealer_id);

        if (!$dealer_id || !$ddealer) {
            show_error('查無經銷人員資料');
        }

        $this->load->model('retailer_group_model');
        $groups = $this->retailer_group_model->getGroupSelect($ddealer['retailer']['retailer_role_id'], (empty($ddealer['retailer']['level']['retailer_level_type_id']) ? null : $ddealer['retailer']['level']['retailer_level_type_id']));

        if ($this->input->post()) {
            $this->form_validation->set_rules('retailer_group_id', '群組', 'required|integer|in_list[' . implode(',',array_keys($groups)) . ']');
            $this->form_validation->set_rules('password', '密碼', '<PASSWORD>]');
            $this->form_validation->set_rules('password_confirm', '<PASSWORD>', 'min_length[6]|matches[password]');
            $this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
            $this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
            $this->form_validation->set_rules('isLocked', '稽核帳號', 'required|integer|in_list[0,1]');

            if ($this->form_validation->run() !== FALSE) {
                $update_data = [
                    'retailer_group_id' => $this->input->post('retailer_group_id'),
                    'name' => $this->input->post('name'),
                    'gender' => $this->input->post('gender'),
                    'isLocked' => $this->input->post('isLocked'),
                ];
                if ($this->input->post('password')){
                    $update_data['password'] = $this->authentic->_mix($this->input->post('password'));
                }
                $this->dealer_model->update($update_data, ['id' => $dealer_id]);

                redirect(base_url('/capital_dealer/overview/' . $ddealer['retailer_id']));
            }
        }

        $data = [
            'groups' => $groups,
            'ddealer' => $ddealer,
            'title' => '編輯經銷人員帳號',
            'view' => 'capital/dealer/edit',
        ];

        $this->_preload($data);
    }

    public function cancel($dealer_id)
    {
        $dealer = $this->dealer_model
            ->get($dealer_id);

        if (!$dealer_id || !$dealer) {
            show_error('查無經銷人員資料');
        }

        if ($dealer_id == $this->dealer['id']){
            show_error('不能刪除自己');
        }

        $retailer = $this->retailer_model
            ->get($dealer['retailer_id']);

        if ($retailer && $retailer['contact_dealer_id'] == $dealer_id){
            show_error('預設經銷人員不能刪除');
        }

        $this->dealer_model->delete($dealer_id);

        redirect(base_url('/capital_dealer/overview/' . $dealer['retailer_id']));
    }
}

?><file_sep>/application/views/guest/cart.php
<div class="container">
    <h1 class="mb-4">訂貨單
        <button type="button" class="btn btn-success float-right" data-toggle="modal"
                data-target="#levelDescriptionModal">
            <?= $guest['retailer_level_type']['title'] ?>訂貨規則
        </button>
    </h1>

    <form method="post" id="purchaseForm">

        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th>訂貨日期</th>
                <td colspan="3"><?= date('Y-m-d') ?></td>
            </tr>
            <tr>
                <th>經銷商初次登入身份</th>
                <td colspan="3">
                    <select id="retailer_level_id" name="retailer_level_id" class="form-control" required>
                        <?php
                        foreach ($guest['levels'] as $level_id => $level){
                            ?>
                            <option value="<?=$level_id?>" data-discount="<?=$level['discount']?>" data-first-threshold="<?=$level['firstThreshold']?>" data-month-threshold="<?=$level['monthThreshold']?>" <?php if ($level_id == $guest['level']['id']){ echo 'selected';} ?>><?=$level['title']?></option>
                            <?php
                        }
                        ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th>首次進貨門檻</th>
                <td>
                    <input type="number" class="form-control text-right" id="firstThreshold" name="firstThreshold" required min="0"<?php if ($guest['sales_dealer']['retailer_group_id'] != 4){ echo ' readonly'; } ?> />
                </td>
                <th>每月進貨門檻</th>
                <td>
                    <input type="number" class="form-control text-right" id="monthThreshold" name="monthThreshold" required min="0"<?php if ($guest['sales_dealer']['retailer_group_id'] != 4){ echo ' readonly'; } ?> />
                </td>
            </tr>
            <tr>
                <th>進貨折扣</th>
                <td>
                    <div class="input-group">
                        <input type="number" class="form-control text-right" id="discount" name="discount" required min="1" max="100"<?php if ($guest['sales_dealer']['retailer_group_id'] != 4){ echo ' readonly'; } ?> />
                        <div class="input-group-append">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                </td>

                <th>散裝進貨資格</th>
                <td>
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="isAllowBulk" id="isAllowBulk_1"
                                   value="1"<?php if ($guest['sales_dealer']['retailer_group_id'] != 4){ echo ' disabled'; } ?>>
                            <label class="form-check-label" for="isAllowBulk_1">是</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="isAllowBulk" id="isAllowBulk_0"
                                   value="0" checked<?php if ($guest['sales_dealer']['retailer_group_id'] != 4){ echo ' disabled'; } ?>>
                            <label class="form-check-label" for="isAllowBulk_0">否</label>
                        </div>
                    </div>
                </td>
            </tr>
        </table>

        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th>項次</th>
                <th>貨品編號</th>
                <th>貨品名稱</th>
                <th>單價(含稅)</th>
                <th>包裝數量</th>
                <th>訂購數量</th>
                <th>金額小計</th>
                <th>折扣</th>
                <th>折扣價</th>
            </tr>
            <?php if ($products) {
                $i = 1;
                foreach ($products as $product_id => $product) {
                    ?>
                    <tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
                        <td class="text-center"><?= $i ?></td>
                        <td><?= $product['p_num'] ?></td>
                        <td>
                            <?= $product['pdName'] ?> <?= $product['intro2'] ?>
                            <?php if ($product['picture']) { ?>
                                <a class="show_picture" data-toggle="tooltip"
                                   title="<img src='<?= $product['picture'] ?>' />">
                                    <i class="far fa-images"></i>
                                </a>
                            <?php } ?>
                        </td>
                        <td class="item_cash text-right">$<?= number_format($product['pdCash']) ?></td>
                        <td class="text-right"><?= $product['boxAmount'] ?></td>
                        <td>
                            <input type="number" name="items[<?= $product_id ?>][qty]"
                                   min="0" class="itemQty form-control text-right"
                                   data-price="<?= intval($product['pdCash']) ?>"
                                   data-boxamount="<?= intval($product['boxAmount']) ?>"
                                   step="<?= $product['boxAmount'] ?>"
                                   value="<?= $product['qty'] ?>"
                                   style="width: 120px;"
                            />
                        </td>
                        <td class="item_subtotal text-right">
                            <?= ($product['qty'] > 0) ? '$' . number_format($product['qty'] * $product['pdCash']) : '' ?>
                        </td>
                        <td class="item_discount text-right">
                            <?= $guest['level']['discount'] . '%' ?>
                        </td>
                        <td class="item_total text-right">
                            <?= ($product['qty'] > 0) ? '$' . number_format(floor($product['pdCash'] * $guest['level']['discount'] / 100) * $product['qty']) : '' ?>
                        </td>
                    </tr>
                    <?php
                    $i++;
                }
            }
            ?>
            <tr>
                <td colspan="5" class="text-right font-weight-bold">小計</td>
                <td id="total_qty_text" class="text-right font-weight-bold"></td>
                <td id="total_subtotal_text" class="text-right font-weight-bold"></td>
                <td></td>
                <td id="total_text" class="text-right font-weight-bold"></td>
            </tr>
            <tr>
                <td colspan="5" class="text-right">備註</td>
                <td colspan="4">
                    <textarea rows="4" name="memo"
                              class="form-control"><?= $guest['purchase']['memo'] ?></textarea>
                </td>
            </tr>
        </table>

        <div class="form-group text-center">
            <input type="submit" class="btn btn-success mr-2" value="填寫經銷商基本資料"/>
            <a href="<?= base_url('/auth/logout') ?>" class="btn btn-info">取消/返回登入頁面</a>
            <input type="hidden" id="totalQty" value="0"/>
            <input type="hidden" id="subtotal" value="0"/>
            <input type="hidden" id="retailer_level_type" value="<?=$guest['retailer_level_type']['type']?>"/>
        </div>
    </form>
</div>


<div class="modal fade" id="levelDescriptionModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?= $guest['retailer_level_type']['title'] ?>訂貨規則</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <table class="table table-bordered">
                    <tbody>
                    <tr>
                        <td>經銷商類別</td>
                        <td>代碼</td>
                        <td>進貨折數</td>
                        <td>首次進貨門檻</td>
                        <td>每月進貨門檻</td>
                        <td>保證金</td>
                        <td>輔銷人輔導金(經銷商)</td>
                        <td>輔銷人輔導金(總經銷人員或股東)</td>
                        <td>輔銷人輔導金(皮瑪斯門市人員或股東)</td>
                        <td></td>
                    </tr>
                    <?php foreach ($guest['levels'] as $level){ ?>
                    <tr>
                        <td><?=$level['title']?></td>
                        <td><?=$guest['retailer_level_type']['type'] . ' ' . $level['code']?></td>
                        <td>定價<?=$level['discount']?>%</td>
                        <td>$<?=number_format($level['firstThreshold'])?></td>
                        <td>$<?=number_format($level['monthThreshold'])?>/月</td>
                        <td>$<?=number_format($level['guarantee'])?></td>
                        <td><?=$level['commission_rate']?>%</td>
                        <td><?=$level['commission_rate']?>%</td>
                        <td><?=$level['commission_rate']?>%</td>
                        <td><?=$level['remark']?></td>
                    </tr>
                    <?php } ?>
                    </tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
    var retailer_levels = <?=json_encode($guest['levels'])?>;
    $().ready(function () {
        $('a.show_picture').tooltip({
            animated: 'fade',
            placement: 'top',
            html: true
        });

        $('#retailer_level_id').change(function () {
            var firstThreshold = $(this).find('option:selected').data('first-threshold');
            var monthThreshold = $(this).find('option:selected').data('month-threshold');
            var discount = $(this).find('option:selected').data('discount');
            var retailer_level_type = $('#retailer_level_type').val();

            $('#firstThreshold').val(firstThreshold);
            $('#monthThreshold').val(monthThreshold);
            $('#discount').val(discount);

            $('input[name="isAllowBulk"]').trigger('change');

            calc_total();
        });

        $('input[name="isAllowBulk"]').change(function () {
            var isAllowBulk = parseInt($('input[name="isAllowBulk"]:checked').val()) || 0;
            var enableStep = isAllowBulk ? false : true;

            $('#purchaseForm input.itemQty').each(function () {
                var step = enableStep ? $(this).data('boxamount') : 1;
                $(this).attr('step', step);
            });
        });

        $('#retailer_level_id').trigger('change');

        $('#purchaseForm input.itemQty, #discount').change(function () {
            calc_total();
        });

        function calc_total() {
            var totalQty = 0;
            var subtotal = 0;
            $('#purchaseForm input.itemQty').each(function () {
                var item = $(this).parents('tr');
                var qty = parseInt($(this).val()) || 0;
                var price = parseInt($(this).data('price'));

                if (qty > 0) {
                    item.find('.item_subtotal').text('$' + numberWithCommas(price * qty));
                    totalQty += qty;
                    subtotal += price * qty;
                } else {
                    item.find('.item_subtotal').text('');
                }
            });

            $('#total_qty_text').text(numberWithCommas(totalQty));
            $('#totalQty').val(totalQty);
            $('#total_subtotal_text').text('$' + numberWithCommas(subtotal));
            $('#subtotal').val(subtotal);

            calc_discount();
        }

        function calc_discount() {
            var total = 0;
            var discount = $('#discount').val();
            if (discount > 100 || discount < 0) {
                discount = 100;
            }
            var discount_text = discount + '%';

            $('#purchaseForm input.itemQty').each(function () {
                var item = $(this).parents('tr');
                var qty = parseInt($(this).val()) || 0;
                var price = parseInt($(this).data('price'));

                item.find('td.item_discount').text(discount_text);
                item_discount = discount;

                if (qty > 0) {
                    var discount_price = Math.floor(price * item_discount / 100) * qty;
                    item.find('td.item_total').text('$' + numberWithCommas(discount_price));
                    total += discount_price;
                } else {
                    item.find('td.item_total').text('');
                }
            });

            $('#total_text').text('$' + numberWithCommas(total));
        }
    });

    function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    $("#purchaseForm").submit(function (e) {
        var totalQty = parseInt($('#totalQty').val()) || 0;
        if (totalQty == 0) {
            alert('請至少進貨一樣商品！');
            return false;
        }

        var subtotal = parseInt($('#subtotal').val()) || 0;
        var firstThreshold = $('#firstThreshold').val();
        if (subtotal < firstThreshold){
            alert('首次進貨門檻必須大於' + firstThreshold);
            return false;
        }

        var match_boxamount = true;
        $('#purchaseForm input.itemQty').each(function () {
            var qty = parseInt($(this).val());
            var boxamount = parseInt($(this).data('boxamount'));
            if (qty > 0 && qty % boxamount !== 0){
                match_boxamount = false;
                return false;
            }
        });

        var is_confirm = false;
        if (!match_boxamount){
            if (confirm('此單非全部都是整箱的倍數的數量，取貨方式限定親自至輔銷單位取貨')){
                is_confirm = true;
            } else {
                return false;
            }
        } else {
            is_confirm = true;
        }

        if (is_confirm) {
            $.each($('input.itemQty'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });
        }
    });
</script><file_sep>/application/models/Confirm_model.php
<?php

class Confirm_model extends MY_Model
{
    public $table = 'olive_confirms';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'audit_retailer_id');
        $this->has_one['coupon'] = array('foreign_model' => 'Coupon_model', 'foreign_table' => 'olive_coupons', 'foreign_key' => 'id', 'local_key' => 'confirm_id');
    }

    public function confirmed($type, $id, $audit = 1, $dealer)
    {
        if (!$type && !$id && !$dealer){
            $this->insert([
                'confirm_type' => $type,
                'confirm_id' => $id,
                'audit_retailer_id' => $dealer['retailer_id'],
                'audit' => (int)$audit,
                'dealer_id' => $dealer['id'],
            ]);
        }
    }
}

?>
<file_sep>/application/views/consumer/paying.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">貨到付款收款作業</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label class="font-weight-bold">付款金額</label>
                    <div>$<?=number_format($order['total'])?></div>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/consumer/payAtShipped')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" name="submit" value="收款無誤" />
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/customer/upgrade.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">符合飄雪白卡資格
                <button type="button" class="btn btn-success float-right" data-toggle="modal"
                        data-target="#levelDescriptionModal">會員資格說明</button>
            </h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>
                <div class="form-group">
                    <label>電話</label>
                    <input name="phone" class="form-control" required value="<?= set_value('phone', $customer['phone']) ?>"/>
                </div>
                <div class="form-group">
                    <label>姓名</label>
                    <input name="name" class="form-control" required value="<?= set_value('name', $customer['name']) ?>"/>
                </div>
                <div class="form-group">
                    <label>性別</label>
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="gender_1"
                                   value="1"<?= set_value('gender', $customer['gender']) == '1' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="gender_1">男</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="gender_0"
                                   value="0"<?= set_value('gender', $customer['gender']) === '0' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="gender_0">女</label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="font-weight-bold">生日</label>
                    <div class="form-row">
                        <div class="col">
                            <select class="form-control" name="birthday_year">
                                <option value="">生日年</option>
                                <?php for ($i = date('Y'); $i > date('Y', strtotime('-100 years')); $i--){ ?>
                                    <option value="<?=$i?>"<?php if (set_value('birthday_year', $customer['birthday_year']) == $i){ echo ' selected'; } ?>><?=$i?></option>
                                <?php } ?>
                            </select>
                        </div>
                        <div class="col">
                            <input id="birthday" name="birthday" class="form-control" value="<?= set_value('birthday', $customer['birthday'] ? date('m/d', strtotime($customer['birthday'])) : '') ?>"/>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" required value="<?= set_value('email', $customer['email']) ?>"/>
                </div>
                <div class="form-group">
                    <label>地址</label>
                    <input name="address" class="form-control" required value="<?= set_value('address', $customer['address']) ?>"/>
                </div>
                <div class="form-group">
                    <div class="float-right">
                        <a id="btn-reject" href="<?=base_url('/customer/consumer/' . $customer['id'])?>" class="btn btn-warning mr-2">否</a>
                        <input type="submit" class="btn btn-success" value="是" />
                    </div>
                    <p>已符合會員資格，是否成為會員？</p>
                </div>
            </form>
        </div>
    </div>
</div>


<div class="modal fade" id="levelDescriptionModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">會員資格說明</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <?php
                if ($levels) {
                    foreach ($levels as $level) {
                        ?>
                        <div class="form-group">
                            <h3><?=$level['title']?></h3>
                            <div>
                                <?=$level['description']?>
                            </div>
                        </div>
                        <?php
                    }
                }
                ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<link rel="stylesheet" href="<?= base_url('/css/datepicker.min.css')?>" />
<script src="<?= base_url('/js/datepicker.min.js')?>"></script>

<script>
    $().ready(function(){
        //只能按是和否
        $('a').each(function(){
            if ($(this).attr('id') != 'btn-reject'){
                $(this).removeAttr('href');
            }
        });

        $("#birthday").datepicker({
            format: 'mm/dd'
        });
    });
</script><file_sep>/application/controllers/Capital_level_type.php
<?php

class Capital_level_type extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_level_type_model');

        $this->session->set_userdata('return_page', base_url('/capital_level/overview'));
    }

    public function overview()
    {
        $total_level_types_count = $this->retailer_level_type_model
            ->count_rows();

        $level_types = $this->retailer_level_type_model
            ->order_by('type', 'asc')
            ->paginate(20, $total_level_types_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_level_type', 'edit')){
            $authority['edit'] = true;
        }

        $data = [
            'level_types' => $level_types,
            'pagination' => $this->retailer_level_type_model->all_pages,
            'authority' => $authority,
            'title' => '經銷類別',
            'view' => 'capital/level_type/overview',
        ];

        $this->_preload($data);
    }

    public function edit($level_type_id)
    {
        $level_type = $this->retailer_level_type_model
            ->get($level_type_id);

        if (!$level_type_id || !$level_type) {
            show_error('查無經銷類別資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('title', '名稱', 'required|max_length[10]');
            if ($this->form_validation->run() !== FALSE) {
                $update_data = [
                    'title' => $this->input->post('title'),
                    'description' => $this->input->post('description'),
                ];
                $this->retailer_level_type_model->update($update_data, ['id' => $level_type_id]);

                redirect(base_url('/capital_level_type/overview/'));
            }
        }

        $data = [
            'level_type' => $level_type,
            'title' => '編輯經銷類別',
            'view' => 'capital/level_type/edit',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/controllers/Dealer.php
<?php

class Dealer extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!$this->dealer = $this->authentic->isLogged()) {
            redirect(base_url('/auth/login'));
        }
    }

    public function edit()
    {
        $this->load->model('retailer_model');
        $this->load->model('dealer_model');
        $dealers = $this->dealer_model->getDealerSelect($this->dealer['retailer_id']);

        if ($this->input->post()) {
            $this->form_validation->set_rules('company', '單位名稱', 'required|max_length[20]');
            $this->form_validation->set_rules('invoice_title', '單位抬頭', 'max_length[20]');
            $this->form_validation->set_rules('identity', '統一編號', 'required|max_length[10]');
            $this->form_validation->set_rules('contact_dealer_id', '單位代表人', 'integer|in_list[' . implode(',',array_keys($dealers)) . ']');
            $this->form_validation->set_rules('phone', '聯絡電話1', 'required|is_natural|max_length[20]');
            $this->form_validation->set_rules('altPhone', '聯絡電話2', 'is_natural|max_length[20]');
            $this->form_validation->set_rules('address', '聯絡地址', 'required|max_length[100]');
            $this->form_validation->set_rules('bank', '收款銀行', 'max_length[100]');
            $this->form_validation->set_rules('bank_branch', '分行名', 'max_length[100]');
            $this->form_validation->set_rules('bank_account_title', '收款戶名', 'max_length[100]');
            $this->form_validation->set_rules('bank_account', '收款帳戶', 'max_length[100]');

            if ($this->form_validation->run() !== FALSE) {
                $this->retailer_model->update([
                    'company' => $this->input->post('company'),
                    'invoice_title' => $this->input->post('invoice_title') ? $this->input->post('invoice_title') : null,
                    'bank' => $this->input->post('bank') ? $this->input->post('bank') : null,
                    'bank_branch' => $this->input->post('bank_branch') ? $this->input->post('bank_branch') : null,
                    'bank_account_title' => $this->input->post('bank_account_title') ? $this->input->post('bank_account_title') : null,
                    'bank_account' => $this->input->post('bank_account') ? $this->input->post('bank_account') : null,
                    'identity' => $this->input->post('identity'),
                    'contact_dealer_id' => $this->input->post('contact_dealer_id') ? $this->input->post('contact_dealer_id') : null,
                    'phone' => $this->input->post('phone'),
                    'altPhone' => $this->input->post('altPhone'),
                    'address' => $this->input->post('address'),
                ], ['id' => $this->dealer['retailer_id']]);

                $this->dealer['company'] = $this->input->post('company');
                $this->dealer['invoice_title'] = $this->input->post('invoice_title');
                $this->dealer['identity'] = $this->input->post('identity');
                $this->dealer['contact_dealer_id'] = $this->input->post('contact_dealer_id');
                $this->dealer['phone'] = $this->input->post('phone');
                $this->dealer['altPhone'] = $this->input->post('altPhone');
                $this->dealer['address'] = $this->input->post('address');

                $this->session->set_userdata('dealer', $this->dealer);

                $this->session->set_userdata(array('msg' => '單位資料修改成功'));

                redirect('dealer/edit');
            }
        }

        $this->session->set_userdata('return_page', base_url('/dealer/edit'));

        $retailer = $this->retailer_model
            ->get($this->dealer['retailer_id']);

        $data = [
            'dealers' => $dealers,
            'retailer' => $retailer,
            'title' => '單位資料修改',
            'view' => 'dealer/edit',
        ];
        $this->_preload($data);
    }

    public function profile()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
            $this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');

            if ($this->form_validation->run() !== FALSE) {
                $this->dealer['name'] = $this->input->post('name');
                $this->dealer['gender'] = $this->input->post('gender');

                $this->load->model('dealer_model');

                $this->dealer_model
                    ->update([
                        'name' => $this->dealer['name'],
                        'gender' => $this->dealer['gender'],
                    ], ['id' => $this->dealer['id']]);

                $this->session->set_userdata('dealer', $this->dealer);

                $this->session->set_userdata(array('msg' => '個人資料修改成功'));

                redirect('dealer/profile');
            }
        }

        $this->session->set_userdata('return_page', base_url('/dealer/edit'));

        $data = [
            'title' => '個人資料修改',
            'view' => 'dealer/profile',
        ];
        $this->_preload($data);
    }

    public function password()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('password_old', '密碼', 'required|min_length[6]|callback_check_password');
            $this->form_validation->set_rules('password', '密碼', 'required|min_length[6]');
            $this->form_validation->set_rules('password_confirm', '確認密碼', 'required|min_length[6]|matches[password]');
            if ($this->form_validation->run() !== FALSE) {
                $this->load->model('dealer_model');

                $this->dealer_model
                    ->update([
                        'password' => $this->authentic->_mix($this->input->post("password", true)),
                    ], ['id' => $this->dealer['id']]);

                $this->session->set_userdata(array('msg' => '密碼更新成功'));

                redirect('/dealer/password');
            }
        }

        $this->session->set_userdata('return_page', base_url('/dealer/password'));

        $data = [
            'title' => '密碼修改',
            'view' => 'dealer/password',
        ];
        $this->_preload($data);
    }

    public function check_password($password)
    {
        if ($this->authentic->check_password($password)) {
            return true;
        } else {
            $this->form_validation->set_message('check_password','<PASSWORD>，請重新確認');
            return false;
        }
    }
}

?><file_sep>/application/models/Order_model.php
<?php

class Order_model extends MY_Model
{
    public $table = 'olive_orders';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['items'] = array('Order_item_model', 'order_id', 'id');
        $this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipout_retailer_id');
        $this->has_one['customer'] = array('foreign_model' => 'Customer_model', 'foreign_table' => 'olive_customers', 'foreign_key' => 'id', 'local_key' => 'buyer_id');
        $this->has_one['dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'dealer_id');
        $this->has_one['shipout_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipout_retailer_id');
        $this->has_one['contact'] = array('foreign_model' => 'Order_contact_model', 'foreign_table' => 'olive_order_contacts', 'foreign_key' => 'order_id', 'local_key' => 'id');
        $this->has_one['recipient'] = array('foreign_model' => 'Order_recipient_model', 'foreign_table' => 'olive_order_recipients', 'foreign_key' => 'order_id', 'local_key' => 'id');
        $this->has_many['shipments'] = array('Shipment_model', 'ship_id', 'id');
        $this->has_many['payments'] = array('Payment_model', 'pay_id', 'id');
        $this->has_many['returns'] = array('Order_return_model', 'order_id', 'id');
    }

    public function getNextOrderSerialNum()
    {
        $order = $this
            ->with_trashed()
            ->where('DATE_FORMAT(created_at,"%Y-%m") = "' . date('Y-m') . '"', null, null, false, false, true)
            ->order_by('serialNum', 'desc')
            ->get();

//        echo $this->db->last_query();

        if ($order) {
            $num = (int)$order['serialNum'] + 1;
            return str_pad($num, 5, '0', STR_PAD_LEFT);
        } else {
            return '00001';
        }
    }
}

?>
<file_sep>/application/models/Stock_model.php
<?php

class Stock_model extends MY_Model
{
    public $table = 'olive_stocks';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['product'] = array('foreign_model'=>'Product_model','foreign_table'=>'product','foreign_key'=>'pdId','local_key'=>'product_id');
        $this->has_one['retailer'] = array('foreign_model'=>'Retailer_model','foreign_table'=>'olive_retailers','foreign_key'=>'id','local_key'=>'retailer_id');
    }
}

?>
<file_sep>/application/views/dealer/profile.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">個人基本修改</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>姓名</label>
                    <input name="name" class="form-control" value="<?= set_value('name', $dealer['name']) ?>"/>
                </div>
                <div class="form-group">
                    <label>性別</label>
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="gender_1"
                                   value="1"<?= set_value('gender', $dealer['gender']) == '1' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="gender_1">男</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="gender_0"
                                   value="0"<?= set_value('gender', $dealer['gender']) === '0' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="gender_0">女</label>
                        </div>
                    </div>
                </div>
                <div class="form-group text-center">
                    <input type="submit" class="btn btn-success" value="更新"/>
                </div>
            </form>
        </div>
    </div>
</div>
<file_sep>/application/migrations/001_add_retailer_level.php
<?php
//經銷商規則
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_retailer_level extends CI_Migration
{

    public function up()
    {
        //retailer_roles
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'title' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
            ],
            'account_prefix' => [
                'type' => 'VARCHAR',
                'constraint' => 2,
                'null' => TRUE,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_retailer_roles');


        //retailer_level_type
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'retailer_role_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'type' => array(
                'type' => 'CHAR',
                'constraint' => 1,
                'null' => TRUE,
            ),
            'title' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
            ],
            'description' => [
                'type' => 'text',
                'default' => '',
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_retailer_level_types');


        //retailer_level
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'retailer_level_type_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'code' => array(
                'type' => 'CHAR',
                'constraint' => 1,
                'null' => TRUE,
            ),
            'discount' => [
                'type' => 'INT',
                'constraint' => 3,
                'unsigned' => TRUE,
                'default' => 100,
            ],
            'firstThreshold' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'monthThreshold' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'capital_commission' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'capital_commission_type' => [
                'type' => 'Char',
                'default' => 'P',
            ],
            'sales_commission' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'sales_commission_type' => [
                'type' => 'Char',
                'default' => 'P',
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_retailer_levels');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_retailer_levels');
        $this->dbforge->drop_table('olive_retailer_roles');
        $this->dbforge->drop_table('olive_retailer_level_types');
    }
}<file_sep>/application/migrations/046_update_promote_customer.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_promote_customer extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_promotes', [
            'customer_type' => [
                'type' => 'tinyint',
                'unsigned' => TRUE,
                'constraint' => 1,
                'null' => TRUE,
                'after' => 'limit',
            ],
            'customer_limit' => [
                'type' => 'smallint',
                'unsigned' => TRUE,
                'null' => TRUE,
                'after' => 'customer_type',
            ],
            'customer_start_at' => [
                'type' => 'date',
                'null' => TRUE,
                'after' => 'customer_limit',
            ],
            'customer_end_at' => [
                'type' => 'date',
                'null' => TRUE,
                'after' => 'customer_start_at',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_promotes', 'customer_type');
        $this->dbforge->drop_column('olive_promotes', 'customer_limit');
        $this->dbforge->drop_column('olive_promotes', 'customer_start_at');
        $this->dbforge->drop_column('olive_promotes', 'customer_end_at');
    }
}<file_sep>/application/controllers/Recommend.php
<?php

class Recommend extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged())) {
            redirect(base_url('/'));
        }

        $this->load->model('recommend_model');
        $this->load->model('recommend_template_model');

        $this->session->set_userdata('return_page', base_url('/recommend/overview'));
    }

    public function overview()
    {
        $total_recommends_count = $this->recommend_model
            ->where('isTemp', 0)
            ->count_rows();

        $recommends = $this->recommend_model
            ->where('isTemp', 0)
            ->order_by('id', 'desc')
            ->paginate(20, $total_recommends_count);

        $data = [
            'recommends' => $recommends,
            'pagination' => $this->recommend_model->all_pages,
            'title' => '行銷作業區',
            'view' => 'recommend/overview',
        ];

        $this->_preload($data);
    }

    public function temp()
    {
        $total_recommends_count = $this->recommend_model
            ->where('isTemp', 1)
            ->count_rows();

        $recommends = $this->recommend_model
            ->where('isTemp', 1)
            ->order_by('id', 'desc')
            ->paginate(20, $total_recommends_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('recommend', 'edit')){
            $authority['edit'] = true;
        }

        $data = [
            'recommends' => $recommends,
            'pagination' => $this->recommend_model->all_pages,
            'authority' => $authority,
            'title' => '暫存作業區',
            'view' => 'recommend/temp',
        ];

        $this->_preload($data);
    }

    public function add($template_id = '')
    {
        $template = [];
        $templates = [];

        if ($template_id){
            if ($template_id > 0) {
                $template = $this->recommend_template_model
                    ->where('isConfirmed', 1)
                    ->get($template_id);

                if (!$template) {
                    show_error('查無推薦函資料');
                }
            }

            if ($this->input->post()) {
                $config['upload_path'] = FCPATH . 'uploads/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = 10000000; //10M
                $config['file_ext_tolower'] = true;
                $config['encrypt_name'] = true;
                $this->load->library('upload', $config);

                $picture1 = null;
                $picture2 = null;

                if ($_FILES['picture1'] && $_FILES['picture1']['size']) {
                    if ($this->upload->do_upload('picture1')) {
                        $upload_data = $this->upload->data();
                        $picture1 = '/uploads/' . $upload_data['file_name'];
                    } else {
                        $error[] = strip_tags($this->upload->display_errors());
                    }
                } else {
                    $error[] = '已將簽名之推薦函拍照傳入或掃描傳入電腦中之指定資料夾';
                }

                if ($_POST['hasPicture2'] == 1 && $_FILES['picture2'] && $_FILES['picture2']['size']) {
                    if ($this->upload->do_upload('picture2')) {
                        $upload_data = $this->upload->data();
                        $picture2 = '/uploads/' . $upload_data['file_name'];
                    } else {
                        $error[] = strip_tags($this->upload->display_errors());
                    }
                }

                if (!$error) {
                    $this->recommend_model->insert(
                        [
                            'recommend_template_id' => $template_id,
                            'picture1' => $picture1,
                            'picture2' => $picture2,
                            'isTemp' => empty($_POST['temp_add']) ? 0 : 1,
                        ]
                    );

                    if (empty($_POST['temp_add'])){
                        redirect(base_url('/recommend/overview'));
                    } else {
                        redirect(base_url('/recommend/temp'));
                    }

                }
            }
        } else {
            $total_templates_count = $this->recommend_template_model
                ->where('type', 'I')
                ->where('isConfirmed', 1)
                ->count_rows();

            $templates = $this->recommend_template_model
                ->where('type', 'I')
                ->where('isConfirmed', 1)
                ->order_by('id', 'desc')
                ->paginate(20, $total_templates_count);
        }

        $data = [
            'templates' => $templates,
            'template_id' => $template_id,
            'template' => $template,
            'title' => '來賓推薦作業',
            'view' => 'recommend/add',
        ];

        if (!$template_id) {
            $data['pagination'] = $this->recommend_template_model->all_pages;
        }

        $this->_preload($data);
    }

    public function print_recommend($template_id)
    {
        $template = [];
        if ($template_id > 0) {
            $template = $this->recommend_template_model
                ->get($template_id);

            if (!$template) {
                show_error('查無推薦函資料');
            }
        }

        $data = [
            'template' => $template,
            'title' => '來賓推薦作業列印',
            'view' => 'recommend/print',
        ];

        $this->_preload($data, 'blank');
    }

    public function edit($recommend_id)
    {
        $error = [];

        $recommend = $this->recommend_model
            ->get($recommend_id);

        if (!$recommend_id || !$recommend) {
            show_error('查無行銷作業資料');
        }

        if ($this->input->post()) {
            $config['upload_path'] = FCPATH . 'uploads/';
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size'] = 10000000; //10M
            $config['file_ext_tolower'] = true;
            $config['encrypt_name'] = true;
            $this->load->library('upload', $config);

            $picture1 = $recommend['picture1'];
            $picture2 = $recommend['picture2'];

            if ($_FILES['picture1'] && $_FILES['picture1']['size']) {
                if ($this->upload->do_upload('picture1')) {
                    $upload_data = $this->upload->data();
                    $picture1 = '/uploads/' . $upload_data['file_name'];
                } else {
                    $error[] = strip_tags($this->upload->display_errors());
                }
            }

            if (empty($picture1)){
                $error[] = '必須上傳來賓推薦照片';
            }

            if ($_FILES['picture2'] && $_FILES['picture2']['size']) {
                if ($this->upload->do_upload('picture2')) {
                    $upload_data = $this->upload->data();
                    $picture2 = '/uploads/' . $upload_data['file_name'];
                } else {
                    $error[] = strip_tags($this->upload->display_errors());
                }
            }

            if (!$error) {
                $this->recommend_model->update(
                    [
                        'picture1' => $picture1,
                        'picture2' => empty($picture2) ? null : $picture2,
                        'isTemp' => empty($_POST['temp_add']) ? 0 : 1,
                    ],
                    ['id' => $recommend_id]
                );

                if (empty($_POST['temp_add'])) {
                    redirect(base_url('/recommend/overview'));
                } else {
                    redirect(base_url('/recommend/temp'));
                }
            }
        }

        $data = [
            'recommend' => $recommend,
            'error' => $error,
            'title' => '修改行銷作業',
            'view' => 'recommend/edit',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/views/recommend/print.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <div class="mb-4"><?=empty($template['content']) ? '' : nl2br($template['content'])?></div>
            <div class="font-weight-bold border-bottom pb-5" style="height: 100px;">請於此範圍內簽上姓名及日期</div>
            <p><small>本人簽名同意一個橄欖將本推薦函及相關照片用於其行銷作業上</small></p>
        </div>
    </div>
</div>

<script>
    window.print();
</script><file_sep>/application/models/Retailer_qualification_model.php
<?php

class Retailer_qualification_model extends MY_Model
{
    public $table = 'olive_retailer_qualifications';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
        $this->has_one['level'] = array('foreign_model' => 'Retailer_level_model', 'foreign_table' => 'olive_retailer_levels', 'foreign_key' => 'id', 'local_key' => 'retailer_level_id');
    }
}

?>
<file_sep>/application/models/Expense_model.php
<?php

class Expense_model extends MY_Model
{
    public $table = 'olive_expenses';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
        $this->has_one['shipment'] = array('foreign_model' => 'Shipment_model', 'foreign_table' => 'olive_shipments', 'foreign_key' => 'id', 'local_key' => 'event_id');
    }
}

?>
<file_sep>/application/migrations/037_update_retailer_payment.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_retailer_payment extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_retailers', [
            'bank' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true,
                'after' => 'invoice_title',
            ],
            'bank_branch' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true,
                'after' => 'bank',
            ],
            'bank_account_title' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true,
                'after' => 'bank_branch',
            ],
            'bank_account' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true,
                'after' => 'bank_account_title',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_retailers', 'bank');
        $this->dbforge->drop_column('olive_retailers', 'bank_branch');
        $this->dbforge->drop_column('olive_retailers', 'bank_account_title');
        $this->dbforge->drop_column('olive_retailers', 'bank_account');
    }
}<file_sep>/application/controllers/Transfer.php
<?php

class Transfer extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged())) {
            redirect(base_url('/'));
        }

        $this->load->model('purchase_model');
        $this->load->model('shipment_model');
        $this->load->model('shipment_item_model');
        $this->load->library('stock_lib');
        $this->load->library('purchase_lib');
        $this->load->helper('data_format');

        $this->session->set_userdata('return_page', base_url('/transfer/overview'));
    }

    public function overview()
    {
        $shipin_retailers = $this->purchase_lib->getShipOutListReverse($this->dealer['retailer_id']);

        $search = array(
            'purchaseNum' => $this->input->get('purchaseNum'),
            'created_start' => $this->input->get('created_start'),
            'created_end' => $this->input->get('created_end'),
            'isConfirmed' => $this->input->get('isConfirmed'),
            'isDeleted' => $this->input->get('isDeleted'),
            'isPaid' => $this->input->get('isPaid'),
            'isShipped' => $this->input->get('isShipped'),
            'isReceived' => $this->input->get('isReceived'),
            'shipin_retailer_id' => (int)$this->input->get('shipin_retailer_id'),
        );

        if ($search['purchaseNum'] != ''){
            $this->purchase_model->where('purchaseNum', $search['purchaseNum']);
        }

        if ($search['created_start'] != ''){
            $this->purchase_model->where('created_at', '>=', $search['created_start']);
        }

        if ($search['created_end'] != ''){
            $this->purchase_model->where('created_at', '<=', date('Y-m-d', strtotime($search['created_end'] . " +1 days")));
        }

        if ($search['isConfirmed'] != ''){
            if ($search['isConfirmed'] == '-1'){
                $this->purchase_model->where('isConfirmed IS NULL', null, null, false, false, true);
            } else {
                $this->purchase_model->where('isConfirmed', $search['isConfirmed']);
            }
        }

        if ($search['isDeleted'] != ''){
            if ($search['isDeleted'] == 1){
                $this->purchase_model->where('deleted_at IS NOT NULL', null, null, false, false, true);
            } else {
                $this->purchase_model->where('deleted_at IS NULL', null, null, false, false, true);
            }
        }

        if ($search['isPaid'] != ''){
            $this->purchase_model->where('isPaid', $search['isPaid']);
        }

        if ($search['isShipped'] != ''){
            $this->purchase_model->where('isShipped', $search['isShipped']);
        }

        if ($search['isReceived'] != ''){
            if ($search['isReceived'] == 'isCorrect') {
                $this->purchase_model->where('isShipConfirmed', 1);
            } elseif ($search['isReceived'] == 'isRevised'){
                $this->purchase_model->where('isRevised', 1);
            } elseif ($search['isReceived'] == 'isReturn'){
                $this->purchase_model->where('isReturn', 1);
            } elseif ($search['isReceived'] == 'isAllowance'){
                $this->purchase_model->where('isAllowance', 1);
            }
        }

        if ($search['shipin_retailer_id'] != ''){
            $this->purchase_model->where('retailer_id', $search['shipin_retailer_id']);
        }

        $total_purchases_count = $this->purchase_model
            ->with_trashed()
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->count_rows();

        if ($search['purchaseNum'] != ''){
            $this->purchase_model->where('purchaseNum', $search['purchaseNum']);
        }

        if ($search['created_start'] != ''){
            $this->purchase_model->where('created_at', '>=', $search['created_start']);
        }

        if ($search['created_end'] != ''){
            $this->purchase_model->where('created_at', '<=', date('Y-m-d', strtotime($search['created_end'] . " +1 days")));
        }

        if ($search['isConfirmed'] != ''){
            if ($search['isConfirmed'] == '-1'){
                $this->purchase_model->where('isConfirmed IS NULL', null, null, false, false, true);
            } else {
                $this->purchase_model->where('isConfirmed', $search['isConfirmed']);
            }
        }

        if ($search['isDeleted'] != ''){
            if ($search['isDeleted'] == 1){
                $this->purchase_model->where('deleted_at IS NOT NULL', null, null, false, false, true);
            } else {
                $this->purchase_model->where('deleted_at IS NULL', null, null, false, false, true);
            }
        }

        if ($search['isPaid'] != ''){
            $this->purchase_model->where('isPaid', $search['isPaid']);
        }

        if ($search['isShipped'] != ''){
            $this->purchase_model->where('isShipped', $search['isShipped']);
        }

        if ($search['isReceived'] != ''){
            if ($search['isReceived'] == 'isCorrect') {
                $this->purchase_model->where('isShipConfirmed', 1);
            } elseif ($search['isReceived'] == 'isRevised'){
                $this->purchase_model->where('isRevised', 1);
            } elseif ($search['isReceived'] == 'isReturn'){
                $this->purchase_model->where('isReturn', 1);
            } elseif ($search['isReceived'] == 'isAllowance'){
                $this->purchase_model->where('isAllowance', 1);
            }
        }

        if ($search['shipin_retailer_id'] != ''){
            $this->purchase_model->where('retailer_id', $search['shipin_retailer_id']);
        }

        $purchases = $this->purchase_model
            ->with_trashed()
            ->with_items()
            ->with_transfer_to()
            ->with_retailer('fields:company')
            ->with_shipout_retailer('fields:company')
            ->with_order_transfer()
            ->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
            ->with_shipments(['non_exclusive_where' => "`ship_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='shipment'"]])
            ->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->order_by($this->purchase_model->get_table_name() . '.id', 'desc')
            ->paginate(20, $total_purchases_count);

        if ($purchases) {
            foreach ($purchases as $key => $purchase) {
                $purchase_lib = new purchase_lib($purchase);
                $purchases[$key]['confirm_label'] = $purchase_lib->generateConfirmLabel();
                $purchases[$key]['paid_label'] = $purchase_lib->generatePaidLabel();
                $purchases[$key]['shipped_label'] = $purchase_lib->generateShippedLabel();
            }
        }

        //權限設定
        $authority = array();
        if ($this->authentic->authority('payment', 'confirm')){
            $authority['payment_confirm'] = true;
        }
        if ($this->authentic->authority('transfer', 'confirm')){
            $authority['confirm'] = true;
        }
        if ($this->authentic->authority('transfer', 'transfer')){
            $authority['transfer'] = true;
        }
        if ($this->authentic->authority('shipment', 'add')){
            $authority['shipment_add'] = true;
        }
        if ($this->authentic->authority('shipment', 'detail')){
            $authority['shipment_detail'] = true;
        }
        if ($this->authentic->authority('transfer', 'detail')){
            $authority['detail'] = true;
        }
        if ($this->authentic->authority('transfer', 'detail2')){
            $authority['detail2'] = true;
        }

        $data = [
            'shipin_retailers' => $shipin_retailers,
            'search' => $search,
            'purchases' => $purchases,
            'pagination' => $this->purchase_model->all_pages,
            'authority' => $authority,
            'title' => '出貨單列表',
            'view' => 'transfer/overview',
        ];

        $this->_preload($data);
    }

    public function detail($purchase_id)
    {
        $purchase = $this->purchase_model
            ->with_trashed()
            ->with_retailer('fields:company,invoice_title')
            ->with_shipin_retailer('fields:company,invoice_title')
            ->with_shipout_retailer('fields:company,invoice_title')
            ->with_order_transfer(['with' =>
                [
                    ['relation' => 'order', 'with' => ['contact']],
                    ['relation' => 'retailer'],
                    ['relation' => 'shipout_retailer'],
                ]
            ])
            ->with_items(['with' =>
                [
                    'relation' => 'product',
                    'with' => ['relation' => 'product_kind', 'fields' => 'ctName']
                ]
            ])
            ->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
            ->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get($purchase_id);

        if (!$purchase_id || !$purchase) {
            show_error('查無出貨單資料');
        }

        $purchase_lib = new purchase_lib($purchase);
        $purchase['paid_label'] = $purchase_lib->generatePaidLabel(true);
        $purchase['confirm_label'] = $purchase_lib->generateConfirmLabel(true);
        $purchase['shipped_label'] = $purchase_lib->generateShippedLabel();
        $shipments = [];
        $allowance_payments = [];
        $total_allowance_payment = 0;

        if ($purchase['isShipped']) {
            $real_shipin_retailer = $purchase['shipin_retailer'];
            $real_shipout_retailer = $purchase['shipout_retailer'];
            if (!is_null($purchase['transfer_id'])){
                $transfer_to_purchase = $this->purchase_model
                    ->with_shipin_retailer('fields:company,invoice_title')
                    ->with_shipout_retailer('fields:company,invoice_title')
                    ->get($purchase['transfer_id']);
                if ($transfer_to_purchase){
                    $real_shipout_retailer = $transfer_to_purchase['shipout_retailer'];
                }
            }

            $this->load->model('payment_model');
            //銷貨折讓
            $payments = $this->payment_model
                ->with_paid_retailer('fields:company,invoice_title')
                ->with_received_retailer('fields:company,invoice_title')
                ->with_confirm(['non_exclusive_where' => "confirm_type='payment'"])
                ->where('pay_type', 'shipment_allowance')
                ->where('pay_id', $purchase_id)
                ->get_all();
            if ($payments) {
                foreach ($payments as $payment){
                    $payment['payment_confirm_label'] = $this->payment_model->generatePaymentConfirmLabel($payment, true);
                    $allowance_payments[] = $payment;

                    if ($payment['active'] && $payment['isConfirmed']) {
                        $total_allowance_payment += $payment['price'];
                    }
                }
            }

            $_shipments = $this->shipment_model
                ->with_expirations(['with' => ['relation' => 'product']])
                ->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
                ->with_shipin_retailer('fields:company,invoice_title')
                ->with_shipout_retailer('fields:company,invoice_title')
                ->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
                ->where('ship_type', 'purchase')
                ->where('ship_id', $purchase_id)
                ->order_by('id', 'asc')
                ->get_all();

            if ($_shipments){
                foreach ($_shipments as $shipment){
                    if ($shipment['shipin_retailer_id'] != $purchase['retailer_id']){
                        $shipment['isReturn'] = true;
                        $shipment['shipout_retailer'] = $real_shipin_retailer;
                        $shipment['shipin_retailer'] = $real_shipout_retailer;
                    } else {
                        $shipment['shipout_retailer'] = $real_shipout_retailer;
                        $shipment['shipin_retailer'] = $real_shipin_retailer;
                    }
                    $shipments[] = $shipment;

                    if (is_null($shipment['shipment_id'])) {
                        $revised = $this->shipment_model
                            ->with_expirations(['with' => ['relation' => 'product']])
                            ->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
                            ->with_shipin_retailer('fields:company,invoice_title')
                            ->with_shipout_retailer('fields:company,invoice_title')
                            ->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
                            ->where('shipment_id', $shipment['id'])
                            ->where('isConfirmed', 0)
                            ->order_by('id', 'asc')
                            ->get_all();

                        if ($revised) {
                            $shipments = array_merge($shipments, $revised);
                        }
                    }
                }
            }

            if ($shipments){
                foreach ( array_reverse($shipments) as $shipment ) {
                    if ($shipment['isConfirmed'] || !empty($shipment['isReturn'])) {
                        foreach ($shipment['expirations'] as $sitem) {
                            foreach ($purchase['items'] as $pkey => $pitem) {
                                if ($sitem['product_id'] == $pitem['product_id']) {
                                    if (!isset($purchase['items'][$pkey]['shipping_qty'])){
                                        $purchase['items'][$pkey]['shipping_qty'] = 0;
                                    }
                                    if (!empty($shipment['isReturn'])){
                                        $purchase['items'][$pkey]['shipping_qty'] -= $sitem['qty'];
                                    } else {
                                        $purchase['items'][$pkey]['shipping_qty'] += $sitem['qty'];
                                    }
                                }
                            }
                        }

                        if (empty($shipment['isReturn'])) {
                            break;
                        }
                    }
                }
            }
        }

        //權限設定
        $authority = array();
        if ($this->authentic->authority('consumer', 'transfer_delivery')){
            $authority['transfer_delivery'] = true;
        }
        if ($this->authentic->authority('shipment', 'confirm_revise')){
            $authority['confirm_revise'] = true;
        }
        if ($this->authentic->authority('shipment', 'confirm_return')){
            $authority['confirm_return'] = true;
        }
        if ($this->authentic->authority('payment', 'add')){
            $authority['payment_add'] = true;
        }

        $data = [
            'purchase' => $purchase,
            'shipments' => $shipments,
            'allowance_payments' => $allowance_payments,
            'total_allowance_payment' => $total_allowance_payment,
            'authority' => $authority,
            'title' => '出貨單詳細資料',
            'view' => 'transfer/detail',
        ];

        $this->_preload($data);
    }

    //很醜的設計，例外處理，有些人不能看到價格
    public function detail2($purchase_id)
    {
        $purchase = $this->purchase_model
            ->with_trashed()
            ->with_retailer('fields:company,invoice_title')
            ->with_shipin_retailer('fields:company,invoice_title')
            ->with_shipout_retailer('fields:company,invoice_title')
            ->with_order_transfer(['with' =>
                [
                    ['relation' => 'order', 'with' => ['contact']],
                    ['relation' => 'retailer'],
                    ['relation' => 'shipout_retailer'],
                ]
            ])
            ->with_items(['with' =>
                [
                    'relation' => 'product',
                    'with' => ['relation' => 'product_kind', 'fields' => 'ctName']
                ]
            ])
            ->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
            ->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get($purchase_id);

        if (!$purchase_id || !$purchase) {
            show_error('查無出貨單資料');
        }

        $purchase_lib = new purchase_lib($purchase);
        $purchase['paid_label'] = $purchase_lib->generatePaidLabel(true);
        $purchase['confirm_label'] = $purchase_lib->generateConfirmLabel(true);
        $purchase['shipped_label'] = $purchase_lib->generateShippedLabel();
        $shipments = [];

        if ($purchase['isShipped']) {
            $real_shipin_retailer = $purchase['shipin_retailer'];
            $real_shipout_retailer = $purchase['shipout_retailer'];
            if (!is_null($purchase['transfer_id'])){
                $transfer_to_purchase = $this->purchase_model
                    ->with_shipin_retailer('fields:company,invoice_title')
                    ->with_shipout_retailer('fields:company,invoice_title')
                    ->get($purchase['transfer_id']);
                if ($transfer_to_purchase){
                    $real_shipout_retailer = $transfer_to_purchase['shipout_retailer'];
                }
            }

            $_shipments = $this->shipment_model
                ->with_expirations(['with' => ['relation' => 'product']])
                ->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
                ->with_shipin_retailer('fields:company,invoice_title')
                ->with_shipout_retailer('fields:company,invoice_title')
                ->where('ship_type', 'purchase')
                ->where('ship_id', $purchase_id)
                ->order_by('id', 'asc')
                ->get_all();

            if ($_shipments){
                foreach ($_shipments as $shipment){
                    if ($shipment['shipin_retailer_id'] != $purchase['retailer_id']){
                        $shipment['isReturn'] = true;
                        $shipment['shipout_retailer'] = $real_shipin_retailer;
                        $shipment['shipin_retailer'] = $real_shipout_retailer;
                    } else {
                        $shipment['shipout_retailer'] = $real_shipout_retailer;
                        $shipment['shipin_retailer'] = $real_shipin_retailer;
                    }
                    $shipments[] = $shipment;

                    if (is_null($shipment['shipment_id'])) {
                        $revised = $this->shipment_model
                            ->with_expirations(['with' => ['relation' => 'product']])
                            ->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
                            ->with_shipin_retailer('fields:company,invoice_title')
                            ->with_shipout_retailer('fields:company,invoice_title')
                            ->where('shipment_id', $shipment['id'])
                            ->where('isConfirmed', 0)
                            ->order_by('id', 'asc')
                            ->get_all();

                        if ($revised) {
                            $shipments = array_merge($shipments, $revised);
                        }
                    }
                }

                if ($shipments){
                    foreach ( array_reverse($shipments) as $shipment ) {
                        if ($shipment['isConfirmed'] || !empty($shipment['isReturn'])) {
                            foreach ($shipment['expirations'] as $sitem) {
                                foreach ($purchase['items'] as $pkey => $pitem) {
                                    if ($sitem['product_id'] == $pitem['product_id']) {
                                        if (!isset($purchase['items'][$pkey]['shipping_qty'])){
                                            $purchase['items'][$pkey]['shipping_qty'] = 0;
                                        }
                                        if (!empty($shipment['isReturn'])){
                                            $purchase['items'][$pkey]['shipping_qty'] -= $sitem['qty'];
                                        } else {
                                            $purchase['items'][$pkey]['shipping_qty'] += $sitem['qty'];
                                        }
                                    }
                                }
                            }

                            if (empty($shipment['isReturn'])) {
                                break;
                            }
                        }
                    }
                }
            }
        }

        $data = [
            'purchase' => $purchase,
            'shipments' => $shipments,
            'title' => '出貨單詳細資料',
            'view' => 'transfer/detail2',
        ];

        $this->_preload($data);
    }

    public function transfer($purchase_id)
    {
        $purchase = $this->purchase_model
            ->with_transfer_from()
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get($purchase_id);

        if (!$purchase_id || !$purchase) {
            show_error('查無訂貨單資料');
        }

        if (!is_null($purchase['transfer_id'])) {
            show_error('已確成立轉單資料');
        }

        if (!is_null($purchase['isConfirmed'])) {
            show_error('已確認過訂貨單資料');
        }

        if ($purchase['shipout_retailer_id'] == 1){
            show_error('總代理不需要轉單');
        }

        $shipout_retailers = $this->purchase_lib->getShipOutList($this->dealer['retailer_id']);

        if ($this->input->post()) {
            $this->form_validation->set_rules('transfer_retailer_id', '轉單對象', 'required|integer|in_list[' . implode(',', array_keys($shipout_retailers)) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $this->purchase_model->transfer_purchase($purchase_id, $this->input->post('transfer_retailer_id'), $this->dealer);

                //如果轉單再轉單，原本的轉單資料變動
                if (!empty($purchase['transfer_from'])){
                    $this->purchase_model->update([
                        'shipin_retailer_id' => $purchase['retailer_id'],
                        'shipin_address' => $purchase['retailer_address'],
                        'invoice_retailer' => null,
                        'invoice_send_retailer' => null,
                    ], ['id' => $purchase_id]);

                    $this->purchase_model->update([
                        'transfer_id' => null,
                    ], ['id' => $purchase['transfer_from']['id']]);
                }

                redirect(base_url('/transfer/overview/'));
            }
        }

        $data = [
            'shipout_retailers' => $shipout_retailers,
            'purchase' => $purchase,
            'title' => '出貨單轉單',
            'view' => 'transfer/transfer',
        ];

        $this->_preload($data);
    }

    public function confirm($purchase_id)
    {
        $purchase = $this->purchase_model
            ->with_retailer('fields:company,invoice_title')
            ->with_shipin_retailer('fields:company,invoice_title')
            ->with_shipout_retailer('fields:company,invoice_title')
            ->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
            ->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
            ->with_shipments(['non_exclusive_where' => "`ship_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='shipment'"]])
            ->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get($purchase_id);

        if (!$purchase_id || !$purchase) {
            show_error('查無訂貨單資料');
        }

        if (!is_null($purchase['isConfirmed'])) {
            show_error('已確認過訂貨單資料');
        }

        if ($this->input->post()) {
            $audit = 0;
            if (isset($_POST['confirmed'])) {
                $audit = 1;
            }

            $this->load->model('confirm_model');

            $this->confirm_model->insert([
                'confirm_type' => 'purchase',
                'confirm_id' => $purchase_id,
                'audit_retailer_id' => $this->dealer['retailer_id'],
                'audit' => $audit,
                'dealer_id' => $this->dealer['id'],
            ]);

            $this->purchase_model->update(['isConfirmed' => $audit], ['id' => $purchase_id]);
        }

        redirect(base_url('/transfer/overview/'));
    }
}

?><file_sep>/application/views/recommend_template/index.php
<div class="container">
    <div class="justify-content-md-center d-flex align-items-center" style="height: 75vh;">
        <div>
            <div class="text-center mb-4">
                <?php if (!empty($authority['inside_add'])){ ?>
                <a href="<?=base_url('/recommend_template/inside_add')?>" class="btn btn-success mr-4">新增內部撰寫之推薦函</a>
                <?php } ?>
                <?php if (!empty($authority['outside_add'])){ ?>
                <a href="<?=base_url('/recommend_template/outside_add')?>" class="btn btn-success">新增外部撰寫之推薦函</a>
                <?php } ?>
            </div>
            <div class="text-center mb-4">
                <?php if (!empty($authority['inside'])){ ?>
                <a href="<?=base_url('/recommend_template/inside')?>" class="btn btn-success mr-4">檢視或修改內部撰寫之推薦函</a>
                <?php } ?>
                <?php if (!empty($authority['outside'])){ ?>
                <a href="<?=base_url('/recommend_template/outside')?>" class="btn btn-success">檢視或修改外部撰寫之推薦函</a>
                <?php } ?>
            </div>
            <div class="text-center">
                <?php if (!empty($authority['confirm'])){ ?>
                <a href="<?=base_url('/recommend_template/confirm')?>" class="btn btn-success mr-4">檢視或修改定案之推薦函</a>
                <?php } ?>
            </div>
        </div>
    </div>
</div><file_sep>/application/migrations/036_update_payment_type.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_payment_type extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_payments', [
            'type_id' => [
                'type' => 'Tinyint',
                'constraint' => 2,
                'unsigned' => TRUE,
                'default' => 1,
                'after' => 'price',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_payments', 'type_id');
    }
}<file_sep>/application/views/coupon/overview.php
<div class="container">
    <h1 class="mb-4"><?= $dealer['company'] ?>貴賓優惠券序號登錄</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">年分/月份</th>
            <th class="text-center">優惠券張數</th>
            <th class="text-center">首張優惠券序號 </th>
            <th class="text-center">末張優惠券序號</th>
            <th></th>
        </tr>
        <?php
        if ($coupons) {
            foreach ($coupons as $coupon) {
        ?>
        <tr>
            <td class="text-center"><?= date('Y年m月', strtotime($coupon['coupon_month'])) ?></td>
            <td class="text-center"><?= ($coupon['qty']) ? $coupon['qty'] : '' ?></td>
            <td class="text-center"><?= $coupon['first_couponNum'] ?></td>
            <td class="text-center"><?= $coupon['last_couponNum'] ?></td>
            <td class="text-center">
                <div class="btn-group">
                    <?php if (!empty($authority['edit']) && empty($coupon['receive_confirm']) && strtotime(date('Y-m-01')) <= strtotime($coupon['coupon_month'])){ ?>
                    <a class="btn btn-warning btn-sm"
                       href="<?= base_url('/coupon/edit/' . (empty($coupon['id']) ? 'month_'.$coupon['coupon_month'] : $coupon['id'])) ?>">
                        <i class="fas fa-edit"></i> 貴賓優惠券序號登錄
                    </a>
                    <?php } ?>
                </div>
            </td>
            <?php
            }
        }
        ?>
    </table>
</div><file_sep>/application/models/Retail_model.php
<?php
class Retail_model extends MY_Model{
    public $table = 'retail';
    public $primary_key = 'rid';

    function __construct(){
        parent::__construct();

        $this->timestamps = false;
        $this->return_as = 'array';
    }
}
?>
<file_sep>/application/views/stock/overview.php
<div class="container">
    <h1 class="mb-4"><?= $retailer['company'] ?>庫存列表</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">項次</th>
            <th class="text-center">貨品編號</th>
            <th class="text-center">貨品名稱</th>
            <th class="text-center">正常品數量</th>
            <th class="text-center">即期品數量</th>
            <th class="text-center">過期品數量</th>
            <th class="text-center">未標到期日數量</th>
            <?php if (!empty($authority['detail'])){ ?>
            <th></th>
            <?php } ?>
        </tr>
        <?php
        if ($products) {
            $i = 1;
            foreach ($products as $product_id => $product) {
        ?>
        <tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
            <td class="text-center"><?= $i ?></td>
            <td class="text-center"><?= $product['p_num'] ?></td>
            <td class="text-center"><?= $product['pdName'] ?> <?= $product['intro2'] ?></td>
            <td class="text-right"><?= $product['stock']['normal']['total'] ?></td>
            <td class="text-right"><?= $product['stock']['nearing']['total'] ?></td>
            <td class="text-right"><?= $product['stock']['expired']['total'] ?></td>
            <td class="text-right"><?= $product['stock']['untag']['total'] ?></td>
            <?php if (!empty($authority['detail'])){ ?>
                <td class="text-center">
                    <div class="btn-group" role="group">
                        <a class="btn btn-info btn-sm" href="<?= base_url('/stock/detail/' . $product_id) ?>">詳細</a>
                    </div>
                </td>
            <?php } ?>
            <?php
                $i++;
            }
        }
        ?>
    </table>
</div><file_sep>/README.md
# pcart


在Cli中，專案目錄下指令 php index.php migrate version XXX

XXX 為Migration版本號碼，目前到69

Seeder 指令 php index.php seeder all
<file_sep>/application/views/capital/promote/method/advance2.php
<div class="container">
    <h1 class="mb-4"><?=$promote['title']?> 滿額折扣設定</h1>

    <form method="post">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group">
            <label>滿額值</label>
            <input type="number" name="limit" class="form-control" required min="1000" max="100000" value="<?= set_value('limit', ($promote_method ? $promote_method['limit'] : '')) ?>" />
        </div>

        <div class="form-group">
            <label>優惠值</label>
            <input type="number" name="discount" class="form-control" required min="50" max="10000" value="<?= set_value('discount', ($promote_method ? $promote_method['discount'] : '')) ?>" />
        </div>

        <div class="form-group">
            <label class="font-weight-bold">適用折扣商品</label>
            <select id="items" name="items[]" class="form-control" multiple>
                <?php foreach ($combos as $combo_id => $combo) { ?>
                    <option value="c_<?= $combo_id ?>" <?php if (set_value('items', $items) && in_array('c_'.$combo_id, set_value('items', $items))){ echo 'selected';} ?>>[組合商品]<?= $combo['name'] ?></option>
                <?php } ?>
                <?php foreach ($products as $product_id => $product) { ?>
                    <option value="p_<?= $product_id ?>" <?php if (set_value('items', $items) && in_array('p_'.$product_id, set_value('items', $items))){ echo 'selected';} ?>><?= $product['pdName']. $product['intro2'] ?></option>
                <?php } ?>
            </select>
            <small>*留空代表全部商品</small>
            <input type="hidden" name="discount_type" value="F" />
        </div>

        <div class="form-group d-flex justify-content-between">
            <a href="<?= base_url('/capital_promote_method/overview/' . $promote['id']) ?>" class="btn btn-secondary">取消</a>
            <input type="submit" class="btn btn-success" value="送出"/>
        </div>
    </form>

</div>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css"
      integrity="<KEY> crossorigin="anonymous"/>
<link rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.10/select2-bootstrap.min.css"
      integrity="<KEY> crossorigin="anonymous"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"
        integrity="<KEY> crossorigin="anonymous"></script>
<script>
    $().ready(function () {
        $('#items').select2({
            theme: "bootstrap",
            multiple: true,
            placeholder: '選擇折扣商品'
        });
    });
</script><file_sep>/application/migrations/058_update_stock_expiry_date.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_stock_expiry_date extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_column('olive_stocks', [
            'expired_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_stocks', 'expired_at');
    }
}<file_sep>/application/controllers/Capital_level.php
<?php

class Capital_level extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_level_model');

        $this->session->set_userdata('return_page', base_url('/capital_level/overview'));
    }

    public function overview()
    {
        $total_levels_count = $this->retailer_level_model
            ->count_rows();

        $levels = $this->retailer_level_model
            ->with_type()
            ->order_by('retailer_level_type_id', 'asc')
            ->order_by('code', 'asc')
            ->paginate(20, $total_levels_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_level', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('capital_level', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('capital_level', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'levels' => $levels,
            'pagination' => $this->retailer_level_model->all_pages,
            'authority' => $authority,
            'title' => '經銷規則',
            'view' => 'capital/level/overview',
        ];

        $this->_preload($data);
    }

    public function add()
    {
        $this->load->model('retailer_level_type_model');
        $level_types = $this->retailer_level_type_model->getTypeSelect();

        if ($this->input->post()) {
            $this->form_validation->set_rules('retailer_level_type_id', '經銷類別', 'required|integer|in_list[' . implode(',',array_keys($level_types)) . ']');
            $this->form_validation->set_rules('code', '代碼', 'required|max_length[200]');
            $this->form_validation->set_rules('discount', '折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
            $this->form_validation->set_rules('firstThreshold', '首次進貨門檻', 'integer');
            $this->form_validation->set_rules('monthThreshold', '每月進貨門檻', 'integer');
            $this->form_validation->set_rules('guarantee', '保證金', 'required|integer');

            if ($this->form_validation->run() !== FALSE) {
                $add_data = [
                    'retailer_level_type_id' => $this->input->post('retailer_level_type_id'),
                    'code' => $this->input->post('code'),
                    'discount' => $this->input->post('discount'),
                    'firstThreshold' => $this->input->post('firstThreshold'),
                    'monthThreshold' => $this->input->post('monthThreshold'),
                    'guarantee' => $this->input->post('guarantee'),
                    'remark' => $this->input->post('remark') ? $this->input->post('remark') : null,
                ];
                $this->retailer_level_model->insert($add_data);

                redirect(base_url('/capital_level/overview/'));
            }
        }

        $data = [
            'level_types' => $level_types,
            'title' => '新增經銷規則',
            'view' => 'capital/level/add',
        ];

        $this->_preload($data);
    }

    public function edit($level_id)
    {
        $level = $this->retailer_level_model
            ->with_type()
            ->get($level_id);

        if (!$level_id || !$level) {
            show_error('查無經銷規則資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('code', '代碼', 'required|max_length[200]');
            $this->form_validation->set_rules('discount', '折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
            $this->form_validation->set_rules('firstThreshold', '首次進貨門檻', 'integer');
            $this->form_validation->set_rules('monthThreshold', '每月進貨門檻', 'integer');
            $this->form_validation->set_rules('guarantee', '保證金', 'required|integer');

            if ($this->form_validation->run() !== FALSE) {
                $update_data = [
                    'code' => $this->input->post('code'),
                    'discount' => $this->input->post('discount'),
                    'firstThreshold' => $this->input->post('firstThreshold'),
                    'monthThreshold' => $this->input->post('monthThreshold'),
                    'guarantee' => $this->input->post('guarantee'),
                    'remark' => $this->input->post('remark') ? $this->input->post('remark') : null,
                ];
                $this->retailer_level_model->update($update_data, ['id' => $level_id]);

//                if (!empty($this->dealer['level']) && $this->dealer['level']['id'] == $level_id) {
//                    $this->dealer['level']['discount'] = $this->input->post('discount');
//                    $this->dealer['level']['discount_text'] = $this->input->post('discount') . '%';
//                    $this->dealer['level']['firstThreshold'] = $this->input->post('firstThreshold') ? $this->input->post('firstThreshold') : null;
//                    $this->dealer['level']['monthThreshold'] = $this->input->post('monthThreshold') ? $this->input->post('monthThreshold') : null;
//                    $this->session->set_userdata('dealer', $this->dealer);
//                }

                redirect(base_url('/capital_level/overview/'));
            }
        }

        $data = [
            'level' => $level,
            'title' => '編輯經銷規則',
            'view' => 'capital/level/edit',
        ];

        $this->_preload($data);
    }

    public function cancel($level_id)
    {
        $level = $this->retailer_level_model
            ->with_type()
            ->get($level_id);

        if (!$level_id || !$level) {
            show_error('查無經銷規則資料');
        }

        $this->load->model('retailer_model');
        $retailers = $this->retailer_model
            ->where('retailer_level_id', $level_id)
            ->get_all();
        if ($retailers){
            $str = '';
            foreach ($retailers as $retailer){
                $str .= $retailer['company'].', ';
            }
            show_error('此經銷規則已有經銷商使用，不能刪除，請先修改以下經銷商(' . $str . ')');
        }

        $this->retailer_level_model->delete($level_id);

        redirect(base_url('/capital_level/overview/'));
    }
}

?><file_sep>/application/controllers/Db.php
<?php

class Db extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }
    }

    public function index()
    {
        $results = [];
        if ($this->input->post()) {
            $this->form_validation->set_rules('query', 'SQL', 'required');

            if ($this->form_validation->run() !== FALSE) {
                $query = $this->db->query($this->input->post('query'));
                if (is_object($query) && $query->num_rows() > 0) {
                    $results = $query->result_array();
                } elseif ($query == '1') {
                    $results[] = '成功';
                }
            }
        }

        $data = [
            'results' => $results,
            'view' => 'db',
        ];

        $this->_preload($data);
    }

    public function info()
    {
        echo phpinfo();
    }
}

?><file_sep>/application/views/capital/retailer/group/overview.php
<div class="container">
    <h1 class="mb-4"><?=$role['title']?>群組列表
        <?php if (!empty($authority['add'])){ ?>
            <a href="<?= base_url('/capital_retailer_group/add/' . $id) ?>" class="btn btn-success float-right"><i
                        class="far fa-plus-square"></i> 新增群組</a>
        <?php } ?>
    </h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">群組名稱</th>
            <th></th>
        </tr>
        <?php
        if ($groups) {
            foreach ($groups as $group) {
                ?>
                <tr>
                    <td class="text-center"><?= $group['title'] ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php if (!empty($authority['edit'])){ ?>
                                <a class="btn btn-info btn-sm"
                                   href="<?= base_url('/capital_retailer_group/edit/' . $group['id']) ?>">編輯</a>
                            <?php } ?>
                        </div>

                    </td>
                </tr>
                <?php
            }
        }
        ?>
    </table>
</div><file_sep>/application/migrations/004_add_confirm.php
<?php
//經銷商訂貨單聯絡資訊
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_confirm extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'confirm_type' => [
                'type' => 'VARCHAR',
                'constraint' => 30,
            ],
            'confirm_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'audit_retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'audit' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'memo' => [
                'type' => 'TEXT',
                'null' => TRUE,
            ],
            'dealer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_confirms');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_confirms');
    }
}<file_sep>/application/views/transfer/transfer.php
<div class="container">
    <h1 class="mb-4">出貨單轉單</h1>

    <?php if (validation_errors()) { ?>
        <div class="alert alert-danger">
            <?= validation_errors() ?>
        </div>
    <?php } ?>

    <form method="post">
        <div class="form-group row">
            <label class="col-sm-2 col-form-label font-weight-bold">轉單對象</label>
            <div class="col-sm-10">
                <select id="transfer_retailer_id" name="transfer_retailer_id" class="form-control" required>
                    <option value=""></option>
                    <?php foreach ($shipout_retailers as $retailer_id => $retailer) { ?>
                        <option value="<?= $retailer_id ?>"><?= $retailer['company'] ?></option>
                    <?php } ?>
                </select>
            </div>
        </div>

        <div class="form-group text-center">
            <a class="btn btn-secondary mr-2" href="<?= base_url('/transfer/overview/') ?>">取消</a>
            <input type="submit" class="btn btn-success" value="確認轉單"/>
        </div>
    </form>
</div><file_sep>/application/controllers/Capital_promote.php
<?php

class Capital_promote extends MY_Controller
{
    protected $dealer;
    protected $customer_type;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_model');
        $this->load->model('promote_model');

        $this->customer_type = [
            null => "全部會員",
            1 => "特定時間加入之新會員",
            2 => "特定時間之舊有會員已轉新會員",
            3 => "員工",
        ];
        $this->session->set_userdata('return_page', base_url('/capital_promote/overview'));
    }

    public function overview()
    {
        $total_promotes_count = $this->promote_model
            ->count_rows();

        $promotes = $this->promote_model
            ->order_by('start_at', 'desc')
            ->paginate(20, $total_promotes_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_promote', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('capital_promote_method', 'overview')){
            $authority['method'] = true;
        }
        if ($this->authentic->authority('capital_promote', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('capital_promote', 'cancel')){
            $authority['cancel'] = true;
        }

        $this->load->helper('data_format');

        $data = [
            'customer_type' => $this->customer_type,
            'promotes' => $promotes,
            'pagination' => $this->promote_model->all_pages,
            'authority' => $authority,
            'title' => '優惠活動列表',
            'view' => 'capital/promote/overview',
        ];

        $this->_preload($data);
    }

    public function add()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('title', '活動名稱', 'required|max_length[100]');
            $this->form_validation->set_rules('start_at', '活動開始', 'required|valid_date');
            $this->form_validation->set_rules('end_at', '活動結束', 'required|valid_date');
            $this->form_validation->set_rules('customer_type', '適用對象', 'integer|in_list[' . implode(',',array_keys($this->customer_type)) . ']');
            $this->form_validation->set_rules('customer_limit', '可享用之優惠次數', 'integer');
            $this->form_validation->set_rules('customer_start_at', '適用對象加入開始時間', 'valid_date');
            $this->form_validation->set_rules('customer_end_at', '適用對象加入結束時間', 'valid_date');
            $this->form_validation->set_rules('go_with_member', '會員優惠同時使用', 'integer');
            $this->form_validation->set_rules('go_with_coupon', '貴賓優惠券同時使用', 'integer');

            if ($this->form_validation->run() !== FALSE) {
                $exclude_retailers = (array)$this->input->post('exclude_retailers');

                $insert_options = [
                    'title' => $this->input->post('title'),
                    'start_at' => $this->input->post('start_at'),
                    'end_at' => $this->input->post('end_at'),
                    'exclude_retailers' => $exclude_retailers ? implode(',', $exclude_retailers) : null,
                    'customer_type' => $this->input->post('customer_type') ? $this->input->post('customer_type') : null,
                    'customer_limit' => $this->input->post('customer_limit') ? $this->input->post('customer_limit') : null,
                    'customer_start_at' => null,
                    'customer_end_at' => null,
                    'go_with_member' => empty($this->input->post('go_with_member')) ? 0 : 1,
                    'go_with_coupon' => empty($this->input->post('go_with_coupon')) ? 0 : 1,
                ];

                if (in_array($this->input->post('customer_type'), [1, 2])){
                    $insert_options['customer_start_at'] = $this->input->post('customer_start_at') ? $this->input->post('customer_start_at') : null;
                    $insert_options['customer_end_at'] = $this->input->post('customer_end_at') ? $this->input->post('customer_end_at') : null;
                }

                $promote_id = $this->promote_model->insert($insert_options);

                redirect(base_url('/capital_promote_method/add/' . $promote_id));
            }
        }

        $this->load->helper('form');

        $retailers = $this->retailer_model
            ->order_by('retailer_role_id', 'asc')
            ->order_by('id', 'desc')
            ->get_all();

        $data = [
            'customer_type' => $this->customer_type,
            'retailers' => $retailers,
            'title' => '新增優惠活動',
            'view' => 'capital/promote/add',
        ];

        $this->_preload($data);
    }

    public function edit($promote_id)
    {
        $promote = $this->promote_model
            ->get($promote_id);

        if (!$promote_id || !$promote) {
            show_error('查無優惠活動資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('title', '活動名稱', 'required|max_length[100]');
            $this->form_validation->set_rules('start_at', '活動開始', 'required|valid_date');
            $this->form_validation->set_rules('end_at', '活動結束', 'required|valid_date');
            $this->form_validation->set_rules('customer_type', '適用對象', 'integer|in_list[' . implode(',',array_keys($this->customer_type)) . ']');
            $this->form_validation->set_rules('customer_limit', '可享用之優惠次數', 'integer');
            $this->form_validation->set_rules('customer_start_at', '適用對象加入開始時間', 'valid_date');
            $this->form_validation->set_rules('customer_end_at', '適用對象加入結束時間', 'valid_date');
            $this->form_validation->set_rules('go_with_member', '會員優惠同時使用', 'integer');
            $this->form_validation->set_rules('go_with_coupon', '貴賓優惠券同時使用', 'integer');

            if ($this->form_validation->run() !== FALSE) {
                $exclude_retailers = (array)$this->input->post('exclude_retailers');

                $update_options = [
                    'title' => $this->input->post('title'),
                    'start_at' => $this->input->post('start_at'),
                    'end_at' => $this->input->post('end_at'),
                    'exclude_retailers' => $exclude_retailers ? implode(',', $exclude_retailers) : null,
                    'customer_type' => $this->input->post('customer_type') ? $this->input->post('customer_type') : null,
                    'customer_limit' => $this->input->post('customer_limit') ? $this->input->post('customer_limit') : null,
                    'customer_start_at' => null,
                    'customer_end_at' => null,
                    'go_with_member' => empty($this->input->post('go_with_member')) ? 0 : 1,
                    'go_with_coupon' => empty($this->input->post('go_with_coupon')) ? 0 : 1,
                ];

                if (in_array($this->input->post('customer_type'), [1, 2])){
                    $update_options['customer_start_at'] = $this->input->post('customer_start_at') ? $this->input->post('customer_start_at') : null;
                    $update_options['customer_end_at'] = $this->input->post('customer_end_at') ? $this->input->post('customer_end_at') : null;
                }

                $this->promote_model->update($update_options, ['id' => $promote_id]);

                redirect(base_url('/capital_promote/overview/'));
            }
        }

        $retailers = $this->retailer_model
            ->order_by('retailer_role_id', 'asc')
            ->order_by('id', 'desc')
            ->get_all();

        $promote['exclude_retailers'] = explode(',', $promote['exclude_retailers']);

        $data = [
            'customer_type' => $this->customer_type,
            'retailers' => $retailers,
            'promote' => $promote,
            'title' => '編輯優惠活動',
            'view' => 'capital/promote/edit',
        ];

        $this->_preload($data);
    }

    public function cancel($promote_id)
    {
        $promote = $this->promote_model
            ->get($promote_id);

        if (!$promote_id || !$promote) {
            show_error('查無優惠活動資料');
        }

        $this->promote_model->delete($promote_id);

        redirect(base_url('/capital_promote/overview/'));
    }
}

?><file_sep>/application/controllers/Recommend_template.php
<?php

class Recommend_template extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged())) {
            redirect(base_url('/'));
        }

        $this->load->model('recommend_template_model');

        $this->session->set_userdata('return_page', base_url('/recommend_template/overview'));
    }

    public function index()
    {
        //權限設定
        $authority = array();
        if ($this->authentic->authority('recommend_template', 'inside_add')){
            $authority['inside_add'] = true;
        }
        if ($this->authentic->authority('recommend_template', 'outside_add')){
            $authority['outside_add'] = true;
        }
        if ($this->authentic->authority('recommend_template', 'inside')){
            $authority['inside'] = true;
        }
        if ($this->authentic->authority('recommend_template', 'outside')){
            $authority['outside'] = true;
        }
        if ($this->authentic->authority('recommend_template', 'confirm')){
            $authority['confirm'] = true;
        }

        $data = [
            'authority' => $authority,
            'title' => '推薦函之增修',
            'view' => 'recommend_template/index',
        ];

        $this->_preload($data);
    }

    public function confirm()
    {
        $total_templates_count = $this->recommend_template_model
            ->where('isConfirmed', 1)
            ->count_rows();

        $templates = $this->recommend_template_model
            ->where('isConfirmed', 1)
            ->order_by('id', 'desc')
            ->paginate(20, $total_templates_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('recommend_template', 'confirm_edit')){
            $authority['edit'] = true;
        }

        $data = [
            'templates' => $templates,
            'pagination' => $this->recommend_template_model->all_pages,
            'authority' => $authority,
            'title' => '檢視或修改定案之推薦函',
            'view' => 'recommend_template/confirm/index',
        ];

        $this->_preload($data);
    }

    public function inside()
    {
        $total_templates_count = $this->recommend_template_model
            ->where('type', 'I')
            ->where('isConfirmed', 0)
            ->count_rows();

        $templates = $this->recommend_template_model
            ->where('type', 'I')
            ->where('isConfirmed', 0)
            ->order_by('id', 'desc')
            ->paginate(20, $total_templates_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('recommend_template', 'inside_add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('recommend_template', 'inside_edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('recommend_template', 'confirming')){
            $authority['confirming'] = true;
        }

        $data = [
            'templates' => $templates,
            'pagination' => $this->recommend_template_model->all_pages,
            'authority' => $authority,
            'title' => '檢視或修改內部撰寫之推薦函',
            'view' => 'recommend_template/inside/index',
        ];

        $this->_preload($data);
    }

    public function outside()
    {
        $total_templates_count = $this->recommend_template_model
            ->where('type', 'O')
            ->where('isConfirmed', 0)
            ->count_rows();

        $templates = $this->recommend_template_model
            ->where('type', 'O')
            ->where('isConfirmed', 0)
            ->order_by('id', 'desc')
            ->paginate(20, $total_templates_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('recommend_template', 'outside_add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('recommend_template', 'outside_edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('recommend_template', 'confirming')){
            $authority['confirming'] = true;
        }

        $data = [
            'templates' => $templates,
            'pagination' => $this->recommend_template_model->all_pages,
            'authority' => $authority,
            'title' => '檢視或修改外部撰寫之推薦函',
            'view' => 'recommend_template/outside/index',
        ];

        $this->_preload($data);
    }

    public function confirm_edit($template_id)
    {
        $template = $this->recommend_template_model
            ->where('isConfirmed', 1)
            ->get($template_id);

        if (!$template_id || !$template) {
            show_error('查無推薦函資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('content', '內容', 'required');

            if ($this->form_validation->run() !== FALSE) {
                $this->recommend_template_model->update(['content' => $this->input->post('content')], ['id' => $template_id]);
                redirect(base_url('/recommend_template/confirm'));
            }
        }

        $data = [
            'template' => $template,
            'title' => '修改定案之推薦函',
            'view' => 'recommend_template/confirm/edit',
        ];

        $this->_preload($data);
    }

    public function inside_add()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('content', '內容', 'required');

            if ($this->form_validation->run() !== FALSE) {
                $this->recommend_template_model->insert(
                    [
                        'type' => 'I',
                        'content' => $this->input->post('content')
                    ]
                );

                if ($_POST['continue_add']){
                    redirect(base_url('/recommend_template/inside_add'), 'refresh');
                } else {
                    redirect(base_url('/recommend_template'));
                }
            }
        }

        $data = [
            'title' => '新增內部撰寫之推薦函',
            'view' => 'recommend_template/inside/add',
        ];

        $this->_preload($data);
    }

    public function inside_edit($template_id)
    {
        $template = $this->recommend_template_model
            ->where('type', 'I')
            ->where('isConfirmed', 0)
            ->get($template_id);

        if (!$template_id || !$template) {
            show_error('查無推薦函資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('content', '內容', 'required');

            if ($this->form_validation->run() !== FALSE) {
                $this->recommend_template_model->update(['content' => $this->input->post('content')], ['id' => $template_id]);
                redirect(base_url('/recommend_template/inside'));
            }
        }

        $data = [
            'template' => $template,
            'title' => '修改定案之推薦函',
            'view' => 'recommend_template/inside/edit',
        ];

        $this->_preload($data);
    }


    public function outside_add()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('content', '內容', 'required');

            if ($this->form_validation->run() !== FALSE) {
                $this->recommend_template_model->insert(
                    [
                        'type' => 'O',
                        'content' => $this->input->post('content')
                    ]
                );

                if ($_POST['continue_add']){
                    redirect(base_url('/recommend_template/outside_add'), 'refresh');
                } else {
                    redirect(base_url('/recommend_template'));
                }
            }
        }

        $data = [
            'title' => '新增外部撰寫之推薦函',
            'view' => 'recommend_template/outside/add',
        ];

        $this->_preload($data);
    }

    public function outside_edit($template_id)
    {
        $template = $this->recommend_template_model
            ->where('type', 'O')
            ->where('isConfirmed', 0)
            ->get($template_id);

        if (!$template_id || !$template) {
            show_error('查無推薦函資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('content', '內容', 'required');

            if ($this->form_validation->run() !== FALSE) {
                $this->recommend_template_model->update(['content' => $this->input->post('content')], ['id' => $template_id]);
                redirect(base_url('/recommend_template/outside'));
            }
        }

        $data = [
            'template' => $template,
            'title' => '修改外部撰寫之推薦函',
            'view' => 'recommend_template/outside/edit',
        ];

        $this->_preload($data);
    }

    public function confirming($template_id)
    {
        $template = $this->recommend_template_model
            ->where('isConfirmed', 0)
            ->get($template_id);

        if (!$template_id || !$template) {
            show_error('查無推薦函資料');
        }

        $this->recommend_template_model->update(['isConfirmed' => 1], ['id' => $template_id]);
        redirect(base_url('/recommend_template'));
    }
}

?><file_sep>/application/views/capital/retailer/add.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">新增單位</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>
                <div class="form-group">
                    <label>單位類型</label>
                    <?php
                    echo form_dropdown('retailer_role_id', $roles, set_value('retailer_role_id'), 'class="form-control"');
                    ?>
                </div>

                <div class="form-group">
                    <label>單位名稱</label>
                    <input name="company" class="form-control" value="<?= set_value('company') ?>" required />
                </div>
                <div class="form-group">
                    <label>單位抬頭</label>
                    <input name="invoice_title" class="form-control" value="<?= set_value('invoice_title') ?>"/>
                </div>
                <div class="form-group">
                    <label>收款銀行</label>
                    <input name="bank" class="form-control" value="<?= set_value('bank') ?>" maxlength="100" />
                </div>
                <div class="form-group">
                    <label>分行名</label>
                    <input name="bank_branch" class="form-control" value="<?= set_value('bank_branch') ?>" maxlength="100" />
                </div>
                <div class="form-group">
                    <label>收款戶名</label>
                    <input name="bank_account_title" class="form-control" value="<?= set_value('bank_account_title') ?>" maxlength="100" />
                </div>
                <div class="form-group">
                    <label>收款帳戶</label>
                    <input name="bank_account" class="form-control" value="<?= set_value('bank_account') ?>" maxlength="100" />
                </div>
                <div class="form-group">
                    <label>統一編號</label>
                    <input name="identity" class="form-control"
                           value="<?= set_value('identity') ?>" required />
                </div>
                <div class="form-group">
                    <label>聯絡電話1</label>
                    <input name="phone" class="form-control"
                           value="<?= set_value('phone', $dealer['phone']) ?>" required />
                </div>
                <div class="form-group">
                    <label>聯絡電話2</label>
                    <input name="altPhone" class="form-control" value="<?= set_value('altPhone') ?>"/>
                </div>
                <div class="form-group">
                    <label>聯絡地址</label>
                    <input name="address" class="form-control" value="<?= set_value('address') ?>" required />
                </div>

                <div class="form-group">
                    <label>首次進貨門檻</label>
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text">$</span>
                        </div>
                        <input type="number" name="firstThreshold" class="form-control text-right" value="<?= set_value('firstThreshold') ?>"/>
                    </div>
                </div>

                <div class="form-group">
                    <label>每月進貨門檻</label>
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text">$</span>
                        </div>
                        <input type="number" name="purchaseThreshold" class="form-control text-right" value="<?= set_value('purchaseThreshold') ?>"/>
                    </div>
                </div>

                <div class="form-group">
                    <label>輔銷單位</label>
                    <?php
                    echo form_dropdown('sales_retailer_id', ['' => ''] + $retailer_selects, set_value('sales_retailer_id'), 'class="form-control"');
                    ?>
                </div>

                <div class="form-group">
                    <label>輔銷人</label>
                    <?php
                    echo form_dropdown('sales_dealer_id', ['' => ''] + $dealer_selects, set_value('sales_dealer_id'), 'class="form-control"');
                    ?>
                </div>

                <div class="form-group">
                    <label>是否管理庫存</label>
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="hasStock" id="hasStock_1"
                                   value="1"<?= set_value('hasStock') == '1' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="hasStock_1">是</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="hasStock" id="hasStock_0"
                                   value="0"<?= set_value('hasStock') != '1' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="hasStock_0">否</label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>是否加總總倉庫存</label>
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="totalStock" id="totalStock_1"
                                   value="1"<?= set_value('totalStock') == '1' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="totalStock_1">是</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="totalStock" id="totalStock_0"
                                   value="0"<?= set_value('totalStock') != '1' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="totalStock_0">否</label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>散裝進貨資格</label>
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="isAllowBulk" id="isAllowBulk_1"
                                   value="1"<?= set_value('isAllowBulk') == '1' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="isAllowBulk_1">是</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="isAllowBulk" id="isAllowBulk_0"
                                   value="0"<?= set_value('isAllowBulk') != '1' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="isAllowBulk_0">否</label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>出貨期限</label>
                    <input type="number" name="eta_days" class="form-control" value="<?= set_value('eta_days') ?>" />
                </div>
                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/capital_retailer/overview/')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="新增"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/capital/combo/add.php
<div class="container">
    <h1 class="mb-4">新增商品組合</h1>

    <form method="post">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group">
            <label class="font-weight-bold">組合名稱</label>
            <input name="name" class="form-control" value="<?= set_value('name') ?>" required/>
        </div>

        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th>項次</th>
                <th>貨品編號</th>
                <th>貨品名稱</th>
                <th>單價(含稅)</th>
                <th>數量</th>
                <th>組合分攤單價</th>
            </tr>
            <?php if ($products) {
                $i = 1;
                foreach ($products as $product_id => $product) {
                    ?>
                    <tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
                        <td class="text-center"><?= $i ?></td>
                        <td><?= $product['p_num'] ?></td>
                        <td>
                            <?= $product['pdName'] ?> <?= $product['intro2'] ?>
                            <?php if ($product['picture']) { ?>
                                <a class="show_picture" data-toggle="tooltip"
                                   title="<img src='<?= $product['picture'] ?>' />">
                                    <i class="far fa-images"></i>
                                </a>
                            <?php } ?>
                        </td>
                        <td><?= $product['pdCash'] ?></td>
                        <td>
                            <input type="number" name="items[<?= $product_id ?>][qty]"
                                   min="1" class="itemQty form-control text-right"
                                   value="<?= set_value('items[' . $product_id . '][qty]') ?>"
                                   style="width: 120px;"
                            />
                        </td>
                        <td>
                            <input type="number" name="items[<?= $product_id ?>][price]"
                                   min="0" class="itemPrice form-control text-right"
                                   value="<?= set_value('items[' . $product_id . '][price]') ?>"
                                   style="width: 120px;"
                            />
                        </td>
                    </tr>
                    <?php
                    $i++;
                }
            }
            ?>
            <tr>
                <td colspan="5" class="text-right font-weight-bold">組合總價</td>
                <td id="total_price" class="text-right font-weight-bold"></td>
            </tr>
        </table>

        <div class="form-group d-flex justify-content-between">
            <a href="<?= base_url('/capital_combo/overview/') ?>" class="btn btn-secondary">取消</a>
            <input type="submit" class="btn btn-success" value="新增"/>
        </div>
    </form>

</div>

<script>
    $().ready(function () {
        calc_total();

        $('a.show_picture').tooltip({
            animated: 'fade',
            placement: 'top',
            html: true
        });

        $('input.itemPrice').change(function () {
            calc_total();
        });

        $('input.itemQty').change(function () {
            calc_total();
        });

        function calc_total() {
            var total = 0;
            $('form input.itemPrice').each(function () {
                var item = $(this).parents('tr');
                var itemPrice = parseInt($(this).val()) || 0;
                var itemQty = parseInt(item.find('input.itemQty').val()) || 0;

                total += itemPrice * itemQty;
            });

            $('#total_price').text('$' + numberWithCommas(total));
        }

        function numberWithCommas(x) {
            return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }

        $("form").find('input[type="submit"]').click(function (e) {
            $.each($('.itemPrice'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });

            $.each($('.itemQty'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });
        });
    });
</script><file_sep>/application/migrations/033_update_purchase.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_purchase extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_purchases', [
            'transfer_id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'null' => TRUE,
                'after' => 'id',
            ],
            'isPayConfirmed' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'paid_at',
            ],
            'isShipConfirmed' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'shipped_at',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_purchases', 'transfer_id');
        $this->dbforge->drop_column('olive_purchases', 'isPayConfirmed');
        $this->dbforge->drop_column('olive_purchases', 'isShipConfirmed');
    }
}<file_sep>/application/models/Promote_use_model.php
<?php

class Promote_use_model extends MY_Model
{
    public $table = 'olive_promote_uses';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['promote'] = array('foreign_model' => 'Promote_model', 'foreign_table' => 'olive_promotes', 'foreign_key' => 'id', 'local_key' => 'promote_id');
        $this->has_one['customer'] = array('foreign_model' => 'Customer_model', 'foreign_table' => 'olive_customers', 'foreign_key' => 'id', 'local_key' => 'customer_id');
    }

    public function getUseTime($promote_id, $customer_id)
    {
        return $this
            ->where('promote_id', $promote_id)
            ->where('customer_id', $customer_id)
            ->count_rows();
    }
}

?>
<file_sep>/application/controllers/Guest.php
<?php

class Guest extends MY_Controller
{
    protected $guest;

    public function __construct()
    {
        parent::__construct();

        $this->guest = $this->session->userdata('guest');

        if (!$this->guest) {
            redirect(base_url('/auth/register'));
        }

        $this->load->model('product_model');
        $this->load->model('dealer_model');
        $this->load->model('retailer_model');
    }

    public function level()
    {
        $this->load->model('retailer_level_type_model');
        $this->load->model('retailer_qualification_model');
        $_retailer_level_types = $this->retailer_level_type_model
            ->with_levels()
            ->get_all();

        $retailer_level_types = [];
        foreach ($_retailer_level_types as $retailer_level_type){
            $retailer_levels = [];
            foreach ($retailer_level_type['levels'] as $l){
                $qualification = $this->retailer_qualification_model
                    ->where('retailer_id', $this->guest['sales_dealer']['retailer_id'])
                    ->where('retailer_level_id', $l['id'])
                    ->get();
                if ($qualification){
                    if ($l['discount'] < 60){
                        $l['commission_rate'] = 2;
                    } elseif ($l['discount'] < 75){
                        $l['commission_rate'] = 3;
                    } else {
                        $l['commission_rate'] = 0;
                    }
                    $retailer_levels[] = $l;
                }
            }

            $retailer_level_type['levels'] = $retailer_levels;
            $retailer_level_types[$retailer_level_type['type']] = $retailer_level_type;
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('type', '經銷商類別', 'trim|required|in_list[' . implode(',', array_keys($retailer_level_types)) . ']');
            if ($this->form_validation->run() !== FALSE) {
                $type = $this->input->post('type');

                if (empty($retailer_level_types[$type]['levels'])){
                    show_error('經銷商規劃中，敬請期待');
                }

                $levels = [];
                foreach ($retailer_level_types[$type]['levels'] as $l) {
                    $l['title'] = $retailer_level_types[$type]['title'] . ' ' . $l['code'];
                    $l['isAllowBulk'] = 0;
                    $levels[$l['id']] = $l;
                }

                $this->load->model('retailer_model');

                $level = [
                    'id' => null,
                    'discount' => 100,
                ];

                $this->guest['levels'] = $levels;

                $this->guest['retailer_level_type'] = [
                    'id' => $retailer_level_types[$type]['id'],
                    'type' => $retailer_level_types[$type]['type'],
                    'title' => $retailer_level_types[$type]['title'],
                ];
                $this->guest['level'] = $level;

                $this->session->set_userdata('guest', $this->guest);

                redirect(base_url('/guest/cart'));
            }
        }

        $data = [
            'retailer_level_types' => $retailer_level_types,
            'title' => '經銷商身份類別選擇',
            'view' => 'guest/level',
        ];
        $this->_preload($data, 'guest');
    }

    public function cart()
    {
        if (empty($this->guest['levels'])) {
            show_error('經銷商規劃中，敬請期待');
        }

        if (empty($this->guest['retailer_level_type'])) {
            show_error('您尚未選擇經銷類別');
        }

        $this->load->model('product_permission_model');
        $products = $this->product_permission_model->getPermissionProducts();

        if (!$products){
            show_error('目前尚無商品可以採購');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('firstThreshold', '首次進貨門檻', 'required|integer|greater_than_equal_to[0]');
            $this->form_validation->set_rules('monthThreshold', '每月進貨門檻', 'required|integer|greater_than_equal_to[0]');
            $this->form_validation->set_rules('isAllowBulk', '散裝進貨資格', 'integer|in_list[0,1]');
            $this->form_validation->set_rules('discount', '進貨折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
            $this->form_validation->set_rules('retailer_level_id', '經銷商類別', 'required|integer|in_list[' . implode(',', array_keys($this->guest['levels'])) . ']');
            $this->form_validation->set_rules('items[][qty]', '訂購數量', 'callback_check_total['. json_encode(['guest_level' => $this->guest['levels'][$this->input->post('retailer_level_id')], 'retailer_level_type' => $this->guest['retailer_level_type'], 'retailer_group_id' => $this->guest['sales_dealer']['retailer_group_id'], 'products' => $products, 'items' => $this->input->post('items'), 'discount' => $this->input->post('discount'), 'isAllowBulk' => $this->input->post('isAllowBulk'), 'firstThreshold' => $this->input->post('firstThreshold')]) .']');

            if ($this->form_validation->run() !== FALSE) {
                $this->guest['purchase']['cart'] = [];

                $items = (array)$this->input->post('items');
                $cart = [];
                $subtotal = 0;
                $total = 0;
                foreach ($items as $product_id => $item) {
                    if ($item['qty'] > 0) {
                        $_data = [
                            'id' => $product_id,
                            'qty' => $item['qty'],
                            'price' => $products[$product_id]['pdCash'],
                            'name' => $products[$product_id]['pdName'] . ' ' . $products[$product_id]['intro2'],
                            'pKind' => $products[$product_id]['pKind'],
                            'p_num' => $products[$product_id]['p_num'],
                            'ctName' => $products[$product_id]['product_kind']['ctName'], //分類
                            'boxAmount' => $products[$product_id]['boxAmount'],
                        ];

                        $subtotal += $item['qty'] * $products[$product_id]['pdCash'];

                        $cart[] = $_data;
                    }
                }

                $this->guest['level'] = $this->guest['levels'][$this->input->post('retailer_level_id')];

                if ($this->guest['sales_dealer']['retailer_group_id'] == 4){ //總監
                    $this->guest['level']['discount'] = $this->input->post('discount');
                    $this->guest['level']['isAllowBulk'] = $this->input->post('isAllowBulk');
                    $this->guest['level']['firstThreshold'] = $this->input->post('firstThreshold');
                    $this->guest['level']['monthThreshold'] = $this->input->post('monthThreshold');
                }

                foreach ($cart as $item) {
                    $discount = $this->guest['level']['discount'];
                    $total += floor($item['price'] * $discount / 100) * $item['qty'];
                }

                $this->guest['purchase'] = [
                    'cart' => $cart,
                    'subtotal' => $subtotal,
                    'total' => $total,
                    'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
                ];

                if ($this->guest['level']['discount'] > 55) {
                    $this->guest['admin_check_discount'] = true;
                }

                switch ($this->guest['sales_dealer']['retailer_role_id']){
                    case 3: //門市
                        if ($this->guest['level']['discount'] > 55) {
                            $this->guest['sales_retailer'] = $this->retailer_model->get($this->guest['sales_dealer']['retailer_id']);
                        } else {
                            $this->guest['sales_retailer'] = $this->retailer_model->get(2);
                        }
                        break;
                    case 5: //經銷商
                        if ($this->guest['level']['discount'] > 55) {
                            $this->guest['sales_retailer'] = $this->retailer_model->get($this->guest['sales_dealer']['sales_retailer']['id']);
                        } else {
                            $this->guest['sales_retailer'] = $this->retailer_model->get(2);
                        }
                        break;
                    default: //總經銷
                        $this->guest['sales_retailer'] = $this->retailer_model->get(2);
                        break;
                }

                $this->session->set_userdata('guest', $this->guest);

                if ($this->guest['admin_check_discount']) {
                    redirect(base_url('/guest/info'));
                } else {
                    redirect(base_url('/guest/adminCheck'));
                }
            }
        }

        foreach ($this->guest['purchase']['cart'] as $item) {
            $products[$item['id']]['qty'] = $item['qty'];
        }

        $data = [
            'guest' => $this->guest,
            'products' => $products,
            'title' => '訂貨單',
            'view' => 'guest/cart',
        ];

        $this->_preload($data, 'guest');
    }

    public function check_total($i, $params)
    {
        $params = json_decode($params, true);
        $guest_level = $params['guest_level'];
        $retailer_level_type = $params['retailer_level_type'];
        $retailer_group_id = $params['retailer_group_id'];
        $discount = $params['discount'];
        $isAllowBulk = empty($params['isAllowBulk']) ? 0 : 1;
        $firstThreshold = $params['firstThreshold'];
        $products = $params['products'];
        $items = $params['items'];
        $subtotal = 0;
        $error = '';
        if ($retailer_group_id == 4){ //總監
            $guest_level['discount'] = $discount;
            $guest_level['firstThreshold'] = $firstThreshold;
            $guest_level['isAllowBulk'] = $isAllowBulk;
        }
        $enableStep = $guest_level['isAllowBulk'] ? false : true;

        foreach ($items as $product_id => $item) {
            if (!isset($products[$product_id])){
                $error = '輸入的貨品有誤';
                break;
            }

            $step = $enableStep ? $products[$product_id]['boxAmount'] : 1;
            if ($item['qty'] % $step){
                $error = '輸入的貨品數量必須為包裝數量倍數';
                break;
            }

            $subtotal += $item['qty'] * $products[$product_id]['pdCash'];
        }

        if (!$error) {
            if ($subtotal < $guest_level['firstThreshold']) {
                $error = '未超過首次進貨門檻，請見訂貨規則';
            }
        }

        if (!$error){
            return true;
        } else {
            $this->form_validation->set_message('check_total', $error);
            return false;
        }
    }

    public function adminCheck()
    {
        if (empty($this->guest['levels'])) {
            show_error('經銷商規劃中，敬請期待');
        }

        if (empty($this->guest['retailer_level_type'])) {
            show_error('您尚未選擇經銷類別');
        }

        if (!$this->guest['purchase']['cart']) {
            show_error('您尚未選購商品');
        }

        if (!$this->guest['sales_retailer']) {
            redirect(base_url('/guest/cart'));
        }

        if ($this->guest['admin_check_discount']) {
            redirect(base_url('/guest/info'));
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('account', '總監代號', 'trim|required');
            $this->form_validation->set_rules('password', '密碼', 'trim|required|callback_check_authentic');

            if ($this->form_validation->run() !== FALSE) {
                $this->guest['admin_check_discount'] = true;

                $this->session->set_userdata('guest', $this->guest);

                redirect(base_url('/guest/info'));
            }
        }

        $data = [
            'title' => '總監登入確認',
            'view' => 'guest/admin_check_login',
        ];
        $this->_preload($data, 'guest');
    }


    public function check_authentic($password)
    {
        $password = $this->authentic->_mix($password);
        $result = $this->dealer_model
            ->where('account', $this->input->post('account'))
            ->where('password', $password)
            ->get();

        if ($result) {
            return true;
        } else {
            $this->form_validation->set_message('check_authentic','您輸入的帳號密碼錯誤，請重新確認');
            return false;
        }
    }

    public function info()
    {
        if (empty($this->guest['levels'])) {
            show_error('經銷商規劃中，敬請期待');
        }

        if (empty($this->guest['retailer_level_type'])) {
            show_error('您尚未選擇經銷類別');
        }

        if (!$this->guest['purchase']['cart']) {
            show_error('您尚未選購商品');
        }

        if (!$this->guest['sales_retailer']) {
            redirect(base_url('/guest/cart'));
        }

        if (!$this->guest['admin_check_discount']) {
            redirect(base_url('/guest/adminCheck'));
        }

        //確認下單
        if ($this->input->post()) {
            $this->guest['retailer']['account'] = $this->input->post('account');
            $this->guest['retailer']['company'] = $this->input->post('company');
            $this->guest['retailer']['identity'] = $this->input->post('identity');
            $this->guest['retailer']['contact'] = $this->input->post('contact');
            $this->guest['retailer']['gender'] = $this->input->post('gender');
            $this->guest['retailer']['phone'] = $this->input->post('phone');
            $this->guest['retailer']['altPhone'] = $this->input->post('altPhone');
            $this->guest['retailer']['address'] = $this->input->post('address');
            $this->guest['purchase']['memo'] = $this->input->post('memo') ? $this->input->post('memo') : null;

            $this->session->set_userdata('guest', $this->guest);

            if (!isset($_POST['checkout'])) {
                redirect(base_url('/guest/cart'));
            } else { //結帳
                $this->form_validation->set_rules('account', '經銷商帳號', 'required|alpha_numeric|min_length[3]|max_length[10]|valid_dealer_account');
                $this->form_validation->set_rules('company', '經銷商名稱', 'required|max_length[20]');
                $this->form_validation->set_rules('identity', '身份證字號/統一編號', 'required|max_length[10]');
                $this->form_validation->set_rules('contact', '經銷商代表人姓名', 'required|max_length[20]');
                $this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
                $this->form_validation->set_rules('phone', '聯絡電話1', 'required|is_natural|max_length[20]');
                $this->form_validation->set_rules('altPhone', '聯絡電話2', 'is_natural|max_length[20]');
                $this->form_validation->set_rules('address', '送貨地址', 'required|max_length[100]');
                $this->form_validation->set_rules('password', '密碼', 'required|min_length[6]');
                $this->form_validation->set_rules('password_confirm', '確認密碼', 'required|min_length[6]|matches[password]');

                if ($this->form_validation->run() !== FALSE) {
                    $this->load->model('purchase_model');
                    $this->load->model('purchase_item_model');

                    $password = $this->input->post('password');

                    $retailer_id = $this->retailer_model->insert([
                        'sales_retailer_id' => $this->guest['sales_retailer']['id'],
                        'sales_dealer_id' => $this->guest['sales_dealer']['id'],
                        'retailer_role_id' => 5, //經銷商
                        'retailer_level_id' => $this->guest['level']['id'],
                        'company' => $this->guest['retailer']['company'],
                        'invoice_title' => $this->guest['retailer']['company'],
                        'identity' => $this->guest['retailer']['identity'],
                        'phone' => $this->guest['retailer']['phone'],
                        'altPhone' => $this->guest['retailer']['altPhone'],
                        'address' => $this->guest['retailer']['address'],
                        'firstThreshold' => $this->guest['level']['firstThreshold'],
                        'purchaseThreshold' => $this->guest['level']['monthThreshold'],
                        'eta_days' => 15,
                        'hasStock' => 1,
                        'isAllowBulk' => $this->guest['level']['isAllowBulk'],
                    ]);

                    $this->load->model('retailer_group_model');
                    $retailer_group = $this->retailer_group_model
                        ->where('retailer_role_id', 5)
                        ->where('retailer_level_type_id', $this->guest['level']['retailer_level_type_id'])
                        ->get();

                    $dealer_id = $this->dealer_model->insert([
                        'retailer_id' => $retailer_id,
                        'retailer_group_id' => empty($retailer_group['id']) ? null : $retailer_group['id'],
                        'account' => $this->guest['retailer']['account'],
                        'password' => $this->authentic->_mix($password),
                        'name' => $this->guest['retailer']['contact'],
                        'gender' => $this->guest['retailer']['gender'],
                    ]);

                    $this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);

                    $this->load->model('retailer_relationship_model');
                    $relationships = [
                        [
                            'relation_type' => 'shipout',
                            'retailer_id' => $retailer_id,
                            'relation_retailer_id' => $this->guest['sales_retailer']['id'],
                            'discount' => $this->guest['level']['discount'],
                        ],
                        [
                            'relation_type' => 'shipin',
                            'retailer_id' => $retailer_id,
                            'relation_retailer_id' => $this->guest['sales_retailer']['id'],
                            'alter_retailer_id' => $retailer_id,
                        ],
                        [
                            'relation_type' => 'invoice',
                            'retailer_id' => $retailer_id,
                            'relation_retailer_id' => $this->guest['sales_retailer']['id'],
                            'alter_retailer_id' => $retailer_id,
                        ],
                        [
                            'relation_type' => 'invoice_send',
                            'retailer_id' => $retailer_id,
                            'relation_retailer_id' => $retailer_id,
                        ],
                        [
                            'relation_type' => 'supervisor',
                            'retailer_id' => $retailer_id,
                            'relation_retailer_id' => $this->guest['sales_retailer']['id'],
                        ]
                    ];

                    if ($this->guest['sales_dealer']['retailer_id'] != $this->guest['sales_retailer']['id']){
                        $rows = $this->retailer_relationship_model
                            ->where('relation_type', 'supervisor')
                            ->where('retailer_id', $this->guest['sales_dealer']['retailer_id'])
                            ->where('relation_retailer_id', $this->guest['sales_retailer']['id'])
                            ->count_rows();
                        if (!$rows) {
                            $relationships[] = [
                                'relation_type' => 'supervisor',
                                'retailer_id' => $this->guest['sales_dealer']['retailer_id'],
                                'relation_retailer_id' => $this->guest['sales_retailer']['id'],
                            ];
                        }

                        if ($this->guest['sales_retailer']['id'] != 2){ //總經銷
                            $rows = $this->retailer_relationship_model
                                ->where('relation_type', 'supervisor')
                                ->where('retailer_id', $this->guest['sales_retailer']['retailer_id'])
                                ->where('relation_retailer_id', 2)
                                ->count_rows();
                            if (!$rows) {
                                $relationships[] = [
                                    'relation_type' => 'supervisor',
                                    'retailer_id' => $this->guest['sales_retailer']['retailer_id'],
                                    'relation_retailer_id' => 2,
                                ];
                            }
                        }
                    }

                    if ($this->guest['sales_retailer']['id'] != 2){ //總經銷
                        $rows = $this->retailer_relationship_model
                            ->where('relation_type', 'supervisor')
                            ->where('retailer_id', $retailer_id)
                            ->where('relation_retailer_id', 2)
                            ->count_rows();
                        if (!$rows) {
                            $relationships[] = [
                                'relation_type' => 'supervisor',
                                'retailer_id' => $retailer_id,
                                'relation_retailer_id' => 2,
                            ];
                        }
                    }

                    foreach ($relationships as $relationship) {
                        $this->retailer_relationship_model->insert($relationship);
                    }

                    $purchaseSerialNum = $this->purchase_model->getNextPurchaseSerialNum();

                    $purchase_id = $this->purchase_model->insert([
                        'retailer_id' => $retailer_id,
                        'retailer_address' => $this->guest['retailer']['address'],
                        'shipout_retailer_id' => $this->guest['sales_retailer']['id'],
                        'shipin_retailer_id' => $retailer_id,
                        'shipin_address' => $this->guest['retailer']['address'],
                        'serialNum' => $purchaseSerialNum,
                        'purchaseNum' => date('Ym') . $purchaseSerialNum,
                        'subtotal' => $this->guest['purchase']['subtotal'],
                        'total' => $this->guest['purchase']['total'],
                        'memo' => $this->guest['purchase']['memo'],
                        'dealer_id' => $dealer_id,
                    ]);

                    $isMatchBox = false;
                    foreach ($this->guest['purchase']['cart'] as $item) {
                        $this->purchase_item_model->insert([
                            'purchase_id' => $purchase_id,
                            'product_id' => $item['id'],
                            'price' => $item['price'],
                            'qty' => $item['qty'],
                            'subtotal' => $item['price'] * $item['qty'],
                            'discount' => $this->guest['level']['discount'],
                            'total' => floor($item['price'] * $this->guest['level']['discount'] / 100) * $item['qty'],
                        ]);

                        if ($item['qty'] % $item['boxAmount'] == 0){
                            $isMatchBox = true;
                        }
                    }

                    $this->purchase_model->update([
                        'isMatchBox' => $isMatchBox,
                    ], ['id' => $purchase_id]);

                    $this->load->model('payment_model');

                    $this->payment_model->insert([
                        'pay_type' => 'purchase',
                        'pay_id' => $purchase_id,
                        'paid_retailer_id' => $retailer_id,
                        'received_retailer_id' => $this->guest['sales_retailer']['id'],
                        'price' => $this->guest['purchase']['total'],
                        'retailer_id' => $retailer_id,
                        'dealer_id' => $dealer_id,
                        'active' => 0,
                    ]);

                    $this->session->set_userdata(array('msg' => '訂購成功，敬請在匯款後，回填付款通知單'));
                    $this->session->unset_userdata('guest');

                    //登入
                    if ($this->authentic->authenticate($this->guest['retailer']['account'], $password)) {
                        redirect('/purchase/detail/' . $purchase_id);
                    } else {
                        show_error('登入時發生錯誤');
                    }
                }
            }
        }

        $products = [];
        foreach ($this->guest['purchase']['cart'] as $item) {
            $products[$item['id']] = $item;
        }

        $data = [
            'guest' => $this->guest,
            'products' => $products,
            'title' => '經銷商基本資料',
            'view' => 'guest/info',
        ];

        $this->_preload($data, 'guest');
    }
}

?><file_sep>/application/views/consumer/trashed.php
<div class="container">
    <h1 class="mb-4"><?= $dealer['company'] ?>取消之消費紀錄</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">刪除人</th>
            <th class="text-center">編號</th>
            <th class="text-center">日期</th>
            <th class="text-center">姓名</th>
            <th class="text-center">電話</th>
            <th class="text-center">總額</th>
            <th class="text-center"></th>
        </tr>
        <?php
        if ($orders) {
            $amount = 0;
            foreach ($orders as $order) {
                $amount += $order['total'];
                ?>
                <tr>
                    <td class="text-center"><?= $order['dealer']['name'] ?></td>
                    <td class="text-center"><?= $order['orderNum'] ?></td>
                    <td class="text-center"><?= $order['created_at'] ?></td>
                    <td class="text-center">
                        <?php if (!empty($authority['customer']) && $order['buyer_id']) { ?>
                            <a href="<?= base_url('/customer/consumer/' . $order['buyer_id']) ?>"><?= $order['contact']['name'] ?></a>
                        <?php } ?>
                    </td>
                    <td class="text-center">
                        <?php if ($order['buyer_id']) { ?>
                            <?= $order['contact']['phone'] ?>
                        <?php } ?>
                    </td>
                    <td class="text-right">$<?= number_format($order['total']) ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php if (!empty($authority['detail'])){ ?>
                            <a class="btn btn-info btn-sm" href="<?= base_url('/consumer/detail/' . $order['id']) ?>">
                                <i class="fas fa-search"></i> 明細
                            </a>
                            <?php } ?>

                            <?php
                            if (!empty($authority['recover']) && $order['shipout_retailer_id'] == $dealer['retailer_id']) { ?>
                            <a class="btn btn-warning btn-sm" href="#"
                               data-href="<?= base_url('/consumer/recover/' . $order['id']) ?>"
                               data-toggle="modal" data-target="#confirm-recover">復原</a>
                            <?php } ?>
                        </div>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="7" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div>

<div class="modal" id="confirm-recover" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">復原確認</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>是否確定復原？</p>
            </div>
            <div class="modal-footer d-flex justify-content-between">
                <button type="button" class="btn" data-dismiss="modal"><i class="fas fa-ban"></i> 取消</button>
                <a href="" class="btn btn-danger btn-confirm">復原</a>
            </div>
        </div>
    </div>
</div>

<script>
    $().ready(function () {
        $('#confirm-recover').on('show.bs.modal', function (e) {
            $(this).find('.btn-confirm').attr('href', $(e.relatedTarget).data('href'));
        });
    });
</script><file_sep>/application/migrations/026_update_customer_level.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_customer_level extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_customer_levels', [
            'description' => [
                'type' => 'text',
                'default' => '',
                'after' => 'discount',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_customer_levels', 'description');
    }
}<file_sep>/application/migrations/003_add_retailer.php
<?php
//經銷商基本資料
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_retailer extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'capital_retailer_id' => [ //皮瑪斯的單位
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'sales_retailer_id' => [ //本單位的輔銷人，是單位
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'retailer_role_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'retailer_level_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'serialNum' => [
                'type' => 'VARCHAR',
                'constraint' => 5,
            ],
            'companyNum' => [
                'type' => 'VARCHAR',
                'constraint' => 7,
                'null' => true,
            ],
            'company' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => true,
            ],
            'invoice_title' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => true,
            ],
            'identity' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
                'null' => true,
            ],
            'contact_dealer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'phone' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => true,
            ],
            'altPhone' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => true,
            ],
            'address' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true,
            ],
            'purchaseThreshold' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'hasStock' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'totalStock' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'eta_days' => [
                'type' => 'int',
                'constraint' => 3,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'isLocked' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_retailers');


        //olive_retailer_relationships
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'relation_type' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => TRUE,
            ],
            'retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'relation_retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'alter_retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'discount' => [
                'type' => 'INT',
                'constraint' => 3,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_retailer_relationships');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_retailers');
        $this->dbforge->drop_table('olive_retailer_relationships');
    }
}<file_sep>/application/migrations/056_create_product_pao.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Create_product_pao extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_column('product', [
            'pao_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('product', 'pao_id');
    }
}<file_sep>/application/models/Shipment_revise_model.php
<?php
class Shipment_revise_model extends MY_Model
{
    public $table = 'olive_shipment_revises';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['shipment'] = array('foreign_model' => 'Shipment_model', 'foreign_table' => 'olive_shipments', 'foreign_key' => 'id', 'local_key' => 'shipment_id');
        $this->has_many['items'] = array('Shipment_revise_item_model', 'shipment_revise_id', 'id');
    }
}

?>
<file_sep>/application/views/recommend/overview.php
<div class="container">
    <h1 class="mb-4">行銷作業區</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">編號</th>
            <th class="text-left w-25">來賓推薦函</th>
            <th class="text-left w-25">來賓推薦照片</th>
        </tr>
        <?php
        if ($recommends) {
            foreach ($recommends as $recommend) {
                ?>
                <tr>
                    <td class="text-center">#<?= $recommend['id'] ?></td>
                    <td class="text-left">
                        <?php if ($recommend['picture1']){ ?>
                            <a href="<?=$recommend['picture1']?>" target="_blank">
                                <img class="img-fluid" src="<?=$recommend['picture1']?>" />
                            </a>
                        <?php } ?>
                    </td>
                    <td class="text-left">
                        <?php if ($recommend['picture2']){ ?>
                            <a href="<?=$recommend['picture2']?>" target="_blank">
                                <img class="img-fluid" src="<?=$recommend['picture2']?>" />
                            </a>
                        <?php } ?>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="4" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div><file_sep>/application/migrations/051_update_promote_gift_choose.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_promote_gift_choose extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_promote_methods', [
            'options' => [
                'type' => 'TEXT',
                'null' => TRUE,
                'after' => 'limit',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_promote_methods', 'options');
    }
}<file_sep>/application/views/layout/guest.php
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="designer" content="cystudio, <EMAIL>" />
    <title><?= $title ?></title>
    <script src="<?= base_url('/js/jquery-3.2.1.slim.min.js')?>"></script>
    <script src="<?= base_url('/js/popper.min.js')?>"></script>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-M5LQ7CP');</script>
    <script src="<?= base_url('/js/bootstrap.min.js')?>"></script>
    <link href="<?= base_url('css/bootstrap.min.css') ?>" rel="stylesheet" type="text/css">
    <link href="<?= base_url('css/styles.css') ?>" rel="stylesheet" type="text/css">
</head>

<body>
    <nav class="navbar navbar-light bg-light mb-4">
        <a class="navbar-brand" href="<?=base_url('/guest/cart')?>">
            <img class="mr-2" height="40" src="<?=base_url('/images/logo.png')?>" />
            一顆橄欖貨物管理系統
        </a>
    </nav>

    <?php if (!empty($msg)){ ?>
        <div class="container">
            <div class="alert alert-info alert-dismissible">
                <?=$msg?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        </div>
    <?php } ?>

<?php
if (isset($data)) {
    $this->load->view($view, $data);
} else {
    $this->load->view($view);
}
?>
</body>
</html>

<file_sep>/application/models/Old_customer_model.php
<?php

class Old_customer_model extends MY_Model
{
    public $table = 'olive_old_customers';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['customer'] = array('foreign_model' => 'Customer_model', 'foreign_table' => 'olive_customers', 'foreign_key' => 'old_customer_id', 'local_key' => 'id');
    }
}

?>
<file_sep>/application/migrations/054_update_retailer_level_guarantee.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_retailer_level_guarantee extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_column('olive_retailer_levels', [
            'guarantee' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'monthThreshold',
            ],
            'remark' => [
                'type' => 'TEXT',
                'null' => TRUE,
                'after' => 'sales_commission_type',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_retailer_levels', 'guarantee');
        $this->dbforge->drop_column('olive_retailer_levels', 'remark');
    }
}<file_sep>/application/models/Promote_model.php
<?php

class Promote_model extends MY_Model
{
    public $table = 'olive_promotes';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['methods'] = array('Promote_method_model', 'promote_id', 'id');
    }

    public function getActivePromotes($retailer_id, $customer = [])
    {
        $_promotes = $this
            ->with_methods()
            ->where('end_at', '>=', date('Y-m-d'))
            ->where('start_at', '<=', date('Y-m-d'))
            ->group_start()
            ->where('exclude_retailers IS NULL', null, null, false, false, true)
            ->where('NOT FIND_IN_SET("' . $retailer_id . '", exclude_retailers)', null, null, true, false, true)
            ->group_end()
            ->order_by('start_at', 'desc')
            ->get_all();

        $promotes = [];
        if ($_promotes) {
            $customer_created_date = $customer ? date('Y-m-d', strtotime($customer['created_at'])) : null;
            $this->load->model('promote_use_model');
            $this->load->model('promote_item_model');
            $this->load->model('promote_item_relative_model');

            foreach ($_promotes as $promote) {
                if (!empty($promote['methods'])){
                    if ($promote['customer_limit'] && $customer){
                        $total_use = $this->promote_use_model->getUseTime($promote['id'], $customer['id']);
                        if ($promote['customer_limit'] <= $total_use){
                            continue;
                        }
                    }

                    if ($promote['customer_type']){
                        switch ($promote['customer_type']){
                            case 1: // 特定時間加入之新會員
                                if (!$customer || !empty($customer['old_customer_id']) || ($promote['customer_start_at'] > $customer_created_date || $promote['customer_end_at'] < $customer_created_date)){
                                    continue 2;
                                }
                                break;
                            case 2: // 特定時間之舊有會員已轉新會員
                                if (!$customer || empty($customer['old_customer_id']) || ($promote['customer_start_at'] > $customer_created_date || $promote['customer_end_at'] < $customer_created_date)){
                                    continue 2;
                                }
                                break;
                        }
                    }

                    $only_gift = true;
                    foreach ($promote['methods'] as $key => $method){
                        if ($method['promote_type_id'] != 3){
                            $only_gift = false;
                        }

                        $items = [];
                        $_product_items = $this->promote_item_model
                            ->with_product(['with' => ['relation' => 'pao']])
                            ->where('promote_method_id', $method['id'])
                            ->where('product_type', 'product')
                            ->get_all();
                        if ($_product_items){
                            foreach ($_product_items as $pg){
                                $items[] = [
                                    'type' => 'product',
                                    'id' => $pg['product_id'],
                                    'name' => $pg['product']['pdName']. $pg['product']['intro2'],
                                    'pao_month' => isset($pg['product']['pao']) ? $pg['product']['pao']['pao_month'] : '',
                                ];
                            }
                        }

                        $_combo_items = $this->promote_item_model
                            ->with_combo()
                            ->where('promote_method_id', $method['id'])
                            ->where('product_type', 'combo')
                            ->get_all();
                        if ($_combo_items){
                            foreach ($_combo_items as $cg){
                                $items[] = [
                                    'type' => 'combo',
                                    'id' => $cg['product_id'],
                                    'name' => $cg['combo']['name'],
                                    'pao_month' => '',
                                ];
                            }
                        }

                        $relatives = [];
                        $_product_relatives = $this->promote_item_relative_model
                            ->with_product()
                            ->where('promote_method_id', $method['id'])
                            ->where('product_type', 'product')
                            ->get_all();
                        if ($_product_relatives){
                            foreach ($_product_relatives as $pg){
                                $relatives[] = [
                                    'type' => 'product',
                                    'id' => $pg['product_id'],
                                    'name' => $pg['product']['pdName']. $pg['product']['intro2'],
                                ];
                            }
                        }

                        $_combo_items = $this->promote_item_relative_model
                            ->with_combo()
                            ->where('promote_method_id', $method['id'])
                            ->where('product_type', 'combo')
                            ->get_all();
                        if ($_combo_items){
                            foreach ($_combo_items as $cg){
                                $relatives[] = [
                                    'type' => 'combo',
                                    'id' => $cg['product_id'],
                                    'name' => $cg['combo']['name'],
                                ];
                            }
                        }

                        if ($promote['methods'][$key]['options']){
                            $promote['methods'][$key]['options'] = unserialize($promote['methods'][$key]['options']);
                        }

                        $promote['methods'][$key]['items'] = $items;
                        $promote['methods'][$key]['relatives'] = $relatives;
                    }
                    $promote['only_gift'] = $only_gift;
                    $promotes[$promote['id']] = $promote;
                }
            }
        }

        return $promotes;
    }
}

?>
<file_sep>/application/views/supervisor/detail.php
<div class="container">
    <h1 class="mb-4 text-center">進貨單詳細資料</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th>進貨單編號</th>
            <td><?= $purchase['purchaseNum'] ?></td>
            <th>訂貨日期</th>
            <td><?= $purchase['created_at'] ?></td>
        </tr>
        <tr>
            <th>出貨單位</th>
            <td><?= $purchase['shipout_retailer']['company'] ?></td>
            <th>出貨單位回覆</th>
            <td><?= $purchase['confirm_label'] ?></td>
        </tr>
        <tr>
            <th>出貨決定</th>
            <td><?= $purchase['shipped_label'] ?></td>
            <th>進貨日期</th>
            <td><?= $purchase['shipped_at'] ?></td>
        </tr>
        <tr>
            <th>進貨單位付款</th>
            <td><?= $purchase['paid_label'] ?></td>
            <th>進貨付款日期</th>
            <td><?= $purchase['paid_at'] ?></td>
        </tr>
        <tr>
            <th>進貨單位</th>
            <td><?= $purchase['retailer']['invoice_title'] ?></td>
            <th>進貨單位地址</th>
            <td><?= $purchase['retailer_address'] ?></td>
        </tr>
        <tr>
            <th>收貨對象</th>
            <td><?= $purchase['shipin_retailer']['invoice_title'] ?></td>
            <th>收貨地址</th>
            <td>
                <?php
                echo $purchase['shipin_address'];
                if (!$purchase['isMatchBox']){
                    echo '<div class="text-danger">取貨方式限定親自至輔銷單位取貨</div>';
                }
                ?>
            </td>
        </tr>
        <?php if ($purchase['isInvoice']) { ?>
            <tr>
                <th>發票對象</th>
                <td colspan="3"><?= $purchase['invoice_retailer'] ?></td>
            </tr>
            <tr>
                <th>發票寄送對象</th>
                <td><?= $purchase['invoice_send_retailer'] ?></td>
                <th>發票寄送地址</th>
                <td><?= $purchase['invoice_send_address'] ?></td>
            </tr>
        <?php } ?>
        <tr>
            <th>進貨方之備註</th>
            <td><?= nl2br($purchase['memo']) ?></td>
            <th>出貨方之備註</th>
            <td><?= !empty($shipment['memo']) ? nl2br($shipment['memo']) : '' ?></td>
        </tr>
    </table>

    <?php if (!empty($purchase['order_transfer'])) { ?>
        <h4 class="mt-5 text-center">A店買B店取貨之紀錄</h4>

        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th class="text-center">日期</th>
                <th class="text-center">取貨人</th>
                <th class="text-center">電話</th>
                <th class="text-center">售出單位</th>
                <th class="text-center">取貨單位</th>
                <th class="text-center">新增進貨單</th>
                <th class="text-center">開立取貨單</th>
                <th class="text-center">是否取貨</th>
            </tr>
            <tr>
                <td class="text-center"><?= date('Y-m-d', strtotime($purchase['order_transfer']['created_at'])) ?></td>
                <td class="text-center"><?= empty($purchase['order_transfer']['order']['contact']['name']) ? '' : $purchase['order_transfer']['order']['contact']['name'] ?></td>
                <td class="text-center"><?= empty($purchase['order_transfer']['order']['contact']['phone']) ? '' : $purchase['order_transfer']['order']['contact']['phone'] ?></td>
                <td class="text-center"><?= $purchase['order_transfer']['retailer']['company'] ?></td>
                <td class="text-center"><?= $purchase['order_transfer']['shipout_retailer']['company'] ?></td>
                <td class="text-center"><?= yesno($purchase['order_transfer']['purchase_id']) ?></td>
                <td class="text-center"><?= yesno($purchase['order_transfer']['isRecorded']) ?></td>
                <td class="text-center"><?= yesno($purchase['order_transfer']['isDeliveried']) ?></td>
            </tr>
        </table>
    <?php } ?>

    <?php
    if ($purchase['items']) {
        ?>
        <h4 class="mt-5 text-center">進貨單詳細商品</h4>
        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th>項次</th>
                <th>貨品編號</th>
                <th>貨品名稱</th>
                <th>單價</th>
                <th>折扣</th>
                <th>訂購數量</th>
                <?php if ($purchase['isShipped']){ ?>
                <th>銷貨數量</th>
                <?php } ?>
                <th>金額小計</th>
            </tr>
            <?php
            if ($purchase['isShipped']){
                $colspan = 7;
            } else {
                $colspan = 6;
            }
            $i = 1;
            foreach ($purchase['items'] as $item) {
                ?>
                <tr<?= ($item['product']['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
                    <td class="text-center"><?= $i ?></td>
                    <td><?= $item['product']['p_num'] ?></td>
                    <td><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
                    <td class="text-right">$<?= number_format($item['price']) ?></td>
                    <td class="text-right"><?= $item['discount'] . '%' ?></td>
                    <td class="text-right"><?= number_format($item['qty']) ?></td>
                    <?php if ($purchase['isShipped']){ ?>
                    <td class="text-right"><?= (!empty($item['shipping_qty'])) ? number_format($item['shipping_qty']) : '' ?></td>
                    <?php } ?>
                    <td class="text-right">$<?= number_format($item['total']) ?></td>
                </tr>
                <?php
                $i++;
            }
            ?>
            <tr>
                <td colspan="<?=$colspan?>" class="text-right font-weight-bold">小計</td>
                <td class="text-right font-weight-bold">$<?= number_format($purchase['total']) ?></td>
            </tr>
            <?php if ($total_allowance_payment > 0) { ?>
                <tr>
                    <td colspan="<?=$colspan?>" class="text-right font-weight-bold">銷貨折讓</td>
                    <td class="text-right font-weight-bold">- $<?= number_format($total_allowance_payment) ?></td>
                </tr>
                <tr>
                    <td colspan="<?=$colspan?>" class="text-right font-weight-bold">總計</td>
                    <td class="text-right font-weight-bold">$<?= number_format($purchase['total'] - $total_allowance_payment) ?></td>
                </tr>
            <?php } ?>
        </table>
        <?php
    }
    ?>

    <?php
    if ($allowance_payments) {
        ?>
        <h4 class="mt-5 text-center">銷貨折讓紀錄</h4>
        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th>日期</th>
                <th>付款單位</th>
                <th>收款單位</th>
                <th>付款方式</th>
                <th>總額</th>
                <th>是否付款</th>
                <th>付款確認</th>
            </tr>
            <?php
            if ($allowance_payments) {
                foreach ($allowance_payments as $ap) {
                    ?>
                    <tr>
                        <td><?= $ap['created_at'] ?></td>
                        <td><?= $ap['paid_retailer']['company'] ?></td>
                        <td><?= $ap['received_retailer']['company'] ?></td>
                        <td><?= paymentType($ap['type_id']) ?></td>
                        <td class="text-right">$<?= number_format($ap['price']) ?></td>
                        <td class="text-center"><?= yesno($ap['active']) ?></td>
                        <td class="text-center"><?= $ap['payment_confirm_label'] ?></td>
                    </tr>
                    <?php
                }
            }
            ?>
        </table>
        <?php
    }
    ?>

    <?php if ($shipments) { ?>
        <h4 class="mt-5 text-center">銷貨紀錄</h4>
        <table class="table table-hover table-bordered table-responsive-sm">
            <thead>
            <tr>
                <th colspan="2">銷貨日期</th>
                <th>寄出單位</th>
                <th>取貨單位</th>
                <th>是否確認</th>
                <th>運費</th>
                <th>備註</th>
                <td></td>
            </tr>
            </thead>
            <tbody>
            <?php
            foreach ($shipments as $shipment) {
                ?>
                <tr>
                    <?php
                    if (!empty($shipment['isReturn'])) {
                        ?>
                        <td>銷貨退回</td>
                        <td><?= $shipment['created_at'] ?></td>
                        <?php
                    } elseif (!empty($shipment['isRevised'])) {
                        ?>
                        <td>已銷貨異動</td>
                        <td><?= $shipment['created_at'] ?></td>
                        <?php
                    } else {
                        ?>
                        <td colspan="2"><?= $shipment['created_at'] ?></td>
                        <?php
                    }
                    ?>
                    <td><?= $shipment['shipout_retailer']['company'] ?></td>
                    <td><?= $shipment['shipin_retailer']['company'] ?></td>
                    <td class="text-center"><?= yesno($shipment['isConfirmed']) ?></td>
                    <td class="text-right">$<?= empty($shipment['expense']) ? 0 : number_format($shipment['expense']['price']) ?></td>
                    <td><?= nl2br($shipment['memo']) ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <button class="btn btn-info" type="button" data-toggle="collapse" data-target="#shipmentItem_<?=$shipment['id']?>" aria-expanded="true">
                                詳細貨品
                            </button>
                        </div>
                    </td>
                </tr>

                <tr id="shipmentItem_<?=$shipment['id']?>" class="collapse table-secondary">
                    <td colspan="8">
                        <?php if (!empty($shipment['expirations'])) { ?>
                            <h5>詳細貨品</h5>
                            <table class="table table-bordered">
                                <thead>
                                <tr>
                                    <th>貨品編號</th>
                                    <th>貨品名稱</th>
                                    <th>到期日</th>
                                    <th>收貨數量</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php
                                foreach ($shipment['expirations'] as $item) {
                                    ?>
                                    <tr>
                                        <td><?= $item['product']['p_num'] ?></td>
                                        <td><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
                                        <td><?= $item['expired_at'] ? $item['expired_at'] : '無標示'?></td>
                                        <td class="text-right"><?= number_format($item['qty']) ?></td>
                                    </tr>
                                    <?php
                                }
                                ?>
                                </tbody>
                            </table>
                        <?php } ?>

                        <?php if (!empty($shipment['revise']) && $shipment['revise']['isConfirmed']){ ?>
                            <h5>異動後貨品</h5>
                            <table class="table table-bordered">
                                <thead>
                                <tr class="table-warning">
                                    <th>貨品編號</th>
                                    <th>貨品名稱</th>
                                    <th>到期日</th>
                                    <th>收貨數量</th>
                                    <th>備註</th>
                                    <th>照片</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php
                                if ($shipment['revise']['items']) {
                                    foreach ($shipment['revise']['items'] as $ri) {
                                        ?>
                                        <tr class="table-warning">
                                            <td><?= $ri['product']['p_num'] ?></td>
                                            <td><?=$ri['product']['pdName'] . $ri['product']['intro2']?></td>
                                            <td><?=$ri['expired_at'] ? $ri['expired_at'] : '無標示'?></td>
                                            <td class="text-right"><?= number_format($ri['qty']) ?></td>
                                            <td><?=nl2br($ri['memo'])?></td>
                                            <td class="text-center">
                                                <?php if (!is_null($ri['memo_file'])){ ?>
                                                    <a href="<?=$ri['memo_file']?>" target="_blank" class="btn btn-info">附件</a>
                                                <?php } ?>
                                            </td>
                                        </tr>
                                        <?php
                                    }
                                }
                                ?>
                                </tbody>
                            </table>
                        <?php } ?>
                    </td>
                </tr>

                <?php if (!empty($shipment['revise']) && !$shipment['revise']['isConfirmed']){ ?>
                    <tr class="table-warning">
                        <td colspan="8">
                            <h5>銷貨異動</h5>
                            <p>確認狀態: <?=yesno($shipment['revise']['isConfirmed'])?></p>
                            <table class="table table-bordered">
                                <thead>
                                <tr class="table-warning">
                                    <th>貨品名稱</th>
                                    <th>到期日</th>
                                    <th>收貨數量</th>
                                    <th>備註</th>
                                    <th>照片</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php
                                if ($shipment['revise']['items']) {
                                    foreach ($shipment['revise']['items'] as $ri) {
                                        ?>
                                        <tr class="table-warning">
                                            <td><?=$ri['product']['pdName'] . $ri['product']['intro2']?></td>
                                            <td><?=$ri['expired_at'] ? $ri['expired_at'] : '無標示'?></td>
                                            <td class="text-right"><?= number_format($ri['qty']) ?></td>
                                            <td><?=nl2br($ri['memo'])?></td>
                                            <td class="text-center">
                                                <?php if (!is_null($ri['memo_file'])){ ?>
                                                    <a href="<?=$ri['memo_file']?>" target="_blank" class="btn btn-info">附件</a>
                                                <?php } ?>
                                            </td>
                                        </tr>
                                        <?php
                                    }
                                }
                                ?>
                                </tbody>
                            </table>
                        </td>
                    </tr>
                <?php } ?>
            <?php } ?>
            </tbody>
        </table>
    <?php } ?>
</div><file_sep>/application/views/customer/consumer.php
<div class="container">
    <h1 class="mb-4">該消費者歷史消費記錄
        <div class="float-right">
            <?php if (!empty($authority['edit'])){ ?>
            <a href="<?= base_url('/customer/edit/' . $customer['id']) ?>" class="btn btn-info"><i class="fas fa-user"></i> 編輯消費者</a>
            <?php } ?>
            <?php if (!empty($authority['consumer_add'])){ ?>
            <a href="<?=base_url('/consumer/add/' . $customer['id']) ?>" class="btn btn-success"><i class="far fa-plus-square"></i> 訂購商品</a>
            <?php } ?>
        </div>

    </h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">編號
                <div class="float-right">
                    <a title="編號降序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=1')?>">
                        <i class="fa fa-sort-amount-down"></i>
                    </a>
                    <a title="編號升序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=2')?>">
                        <i class="fa fa-sort-amount-up"></i>
                    </a>
                </div>
            </th>
            <th class="text-center">日期
                <div class="float-right">
                    <a title="編號降序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=3')?>">
                        <i class="fa fa-sort-amount-down"></i>
                    </a>
                    <a title="編號升序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=4')?>">
                        <i class="fa fa-sort-amount-up"></i>
                    </a>
                </div>
            </th>
            <th class="text-center">總額
                <div class="float-right">
                    <a title="編號降序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=5')?>">
                        <i class="fa fa-sort-amount-down"></i>
                    </a>
                    <a title="編號升序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=6')?>">
                        <i class="fa fa-sort-amount-up"></i>
                    </a>
                </div>
            </th>
            <th class="text-center">營業單位
                <div class="float-right">
                    <a title="編號降序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=7')?>">
                        <i class="fa fa-sort-amount-down"></i>
                    </a>
                    <a title="編號升序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=8')?>">
                        <i class="fa fa-sort-amount-up"></i>
                    </a>
                </div>
            </th>
            <th class="text-center"></th>
        </tr>
        <?php
        if ($orders) {
            $amount = 0;
            foreach ($orders as $order) {
                $amount += $order['total'];
                ?>
                <tr>
                    <td class="text-center"><?= $order['orderNum'] ?></td>
                    <td class="text-center"><?= $order['created_at'] ?></td>
                    <td class="text-right">$<?= number_format($order['total']) ?></td>
                    <td class="text-center"><?= $order['retailer']['company'] ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php if (!empty($authority['consumer_detail'])){ ?>
                            <a class="btn btn-info btn-sm" href="<?= base_url('/consumer/detail/' . $order['id']) ?>">
                                <i class="fas fa-search"></i> 詳細
                            </a>
                            <?php } ?>
                        </div>
                    </td>
                </tr>
                <?php
            }
            ?>
            <tr>
                <th colspan="2" class="text-right">累計消費金額</th>
                <td class="text-right">
                    $<?= number_format($amount) ?>
                </td>
                <td></td>
                <td></td>
            </tr>
            <?php
        } else {
            ?>
            <tr>
                <td colspan="5" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div><file_sep>/application/controllers/Capital_black_vip.php
<?php

class Capital_black_vip extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!$this->dealer = $this->authentic->isLogged()) {
            redirect(base_url('/auth/login'));
        }

        $this->load->model('customer_level_history_model');
        $this->load->model('customer_model');
        $this->load->library('customer_lib');

        $this->session->set_userdata('return_page', base_url('/customer/overview'));
    }

    public function overview()
    {
        $total_customers_count = $this->customer_level_history_model
            ->where('new_customer_level_id', 3)
            ->where('isConfirmed', 0)
            ->count_rows();

        $customers = $this->customer_level_history_model
            ->with_customer()
            ->where('new_customer_level_id', 3)
            ->where('isConfirmed', 0)
            ->order_by('id', 'desc')
            ->paginate(20, $total_customers_count);

        $this->load->helper('data_format');

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_black_vip', 'confirm')){
            $authority['confirm'] = true;
        }
        if ($this->authentic->authority('capital_black_vip', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'customers' => $customers,
            'pagination' => $this->customer_level_history_model->all_pages,
            'authority' => $authority,
            'title' => '曜石黑卡審核遴選',
            'view' => 'capital/black_vip/overview',
        ];

        $this->_preload($data);
    }

    public function confirm($customer_level_history_id)
    {
        $customer_level_history = $this->customer_level_history_model
            ->where('isConfirmed', 0)
            ->get($customer_level_history_id);

        if (!$customer_level_history_id || !$customer_level_history) {
            show_error('查無曜石黑卡審核遴選資料');
        }

        $this->load->model('confirm_model');

        $this->confirm_model->insert([
            'confirm_type' => 'customer_level_history',
            'confirm_id' => $customer_level_history_id,
            'audit_retailer_id' => $this->dealer['retailer_id'],
            'audit' => 1,
            'dealer_id' => $this->dealer['id'],
        ]);

        $this->customer_level_history_model->update(['isConfirmed' => 1], ['id' => $customer_level_history_id]);

        $this->customer_model->update([
            'customer_level_id' => 3,
        ], ['id' => $customer_level_history['customer_id']]);

        redirect(base_url('/capital_black_vip/overview'));
    }

    public function cancel($customer_level_history_id)
    {
        $customer_level_history = $this->customer_level_history_model
            ->where('isConfirmed', 0)
            ->get($customer_level_history_id);

        if (!$customer_level_history_id || !$customer_level_history) {
            show_error('查無曜石黑卡審核遴選資料');
        }

        $this->customer_level_history_model->delete($customer_level_history_id);

        redirect(base_url('/capital_black_vip/overview'));
    }
}

?><file_sep>/application/models/Stock_counting_model.php
<?php

class Stock_counting_model extends MY_Model
{
    public $table = 'olive_stock_countings';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['items'] = array('Stock_counting_item_model', 'stock_counting_id', 'id');
        $this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
        $this->has_one['dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'dealer_id');
    }

    public function getNextSerialNum($counting_reason)
    {
        $stock_counting = $this
            ->with_trashed()
            ->where('DATE_FORMAT(created_at,"%Y-%m-%d") = "' . date('Y-m-d') . '"', null, null, false, false, true)
            ->where('counting_reason', $counting_reason)
            ->order_by('serialNum', 'desc')
            ->get();

        if ($stock_counting) {
            $num = (int)$stock_counting['serialNum'] + 1;
            return str_pad($num, 2, '0', STR_PAD_LEFT);
        } else {
            return '01';
        }
    }
}

?>
<file_sep>/application/models/Dealer_model.php
<?php

class Dealer_model extends MY_Model
{
    public $table = 'olive_dealers';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
        $this->has_one['group'] = array('foreign_model' => 'Retailer_group_model', 'foreign_table' => 'olive_retailer_groups', 'foreign_key' => 'id', 'local_key' => 'retailer_group_id');
    }

    public function getDealerSelect($retailer_id='')
    {
        if ($retailer_id){
            $this->where('retailer_id', $retailer_id);
        } else {
            $this->with_retailer(['fields' => 'company']);
        }
        $_dealers = $this
            ->order_by('retailer_id', 'asc')
            ->order_by('account', 'asc')
            ->get_all();
        $dealers = [];
        if ($_dealers) {
            foreach ($_dealers as $dealer) {
                if ($retailer_id) {
                    $dealers[$dealer['id']] = $dealer['name'];
                } else {
                    $dealers[$dealer['id']] = '(' . $dealer['retailer']['company'] . ')' . $dealer['name'];
                }
            }
        }
        return $dealers;
    }
}

?>
<file_sep>/application/views/capital/product/permission/edit.php
<div class="container">
    <h1 class="mb-4">編輯<?=$product['pdName'] . $product['intro2']?>進貨商品</h1>

    <form method="post">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group">
            <label class="font-weight-bold">可進貨單位</label>
            <select id="include_retailers" name="include_retailers[]" class="form-control" multiple>
                <?php foreach ($retailers as $retailer_id => $retailer_name) { ?>
                    <option value="<?= $retailer_id ?>" <?php if (set_value('include_retailers', $permission['retailers']) && in_array($retailer_id, set_value('include_retailers', $permission['retailers']))){ echo 'selected';} ?>><?= $retailer_name ?></option>
                <?php } ?>
            </select>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">備註</label>
            <textarea rows="4" name="remark" class="form-control"><?= set_value('remark', $permission['remark']) ?></textarea>
        </div>

        <div class="form-group d-flex justify-content-between">
            <a href="<?= base_url('/capital_product/overview/') ?>" class="btn btn-secondary">取消</a>
            <input type="submit" class="btn btn-success" value="更新"/>
        </div>
    </form>

</div>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css"
      integrity="<KEY>="anonymous"/>
<link rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.10/select2-bootstrap.min.css"
      integrity="<KEY> crossorigin="anonymous"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"
        integrity="<KEY> crossorigin="anonymous"></script>
<script>
    $().ready(function () {
        $('#include_retailers').select2({
            theme: "bootstrap",
            multiple: true,
            placeholder: '選擇可進貨單位'
        });
    });
</script><file_sep>/application/views/recommend/edit.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">修改暫存作業</h1>

            <form method="post" enctype="multipart/form-data">
                <?php if ($error) { ?>
                    <div class="alert alert-danger">
                        <?= implode('<br>', $error) ?>
                    </div>
                <?php } ?>

                <div class="card mb-4">
                    <div class="card-header">上傳來賓推薦函或行銷同意書(即無內容之來賓推薦函) / (先行作業：將已簽名之推薦函拍照傳入或掃描傳入電腦中之指定資料夾)</div>
                    <div class="card-body">
                        <?php if ($recommend['picture1']){ ?>
                            <div class="w-25 mb-2">
                                <a href="<?=$recommend['picture1']?>" target="_blank">
                                    <img class="img-fluid" src="<?=$recommend['picture1']?>" />
                                </a>
                            </div>
                        <?php } ?>
                        <input type="file" class="form-control-file" name="picture1" />
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-header">上傳來賓推薦照片 / (先行作業：來賓拍照後將照片傳至電腦)</div>
                    <div class="card-body">
                        <?php if ($recommend['picture2']){ ?>
                            <div class="w-25 mb-2">
                                <a href="<?=$recommend['picture2']?>" target="_blank">
                                    <img class="img-fluid" src="<?=$recommend['picture2']?>" />
                                </a>
                            </div>
                        <?php } ?>
                        <input type="file" class="form-control-file" name="picture2" />
                    </div>
                </div>

                <div class="form-group d-flex justify-content-end">
                    <input type="submit" name="temp_add" class="btn btn-success mr-2" value="暫存 / 先做別的"/>
                    <input type="submit" name="complete_add" class="btn btn-success" value="推薦作業完成"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/controllers/Capital_option.php
<?php

class Capital_option extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('option_model');

        $this->session->set_userdata('return_page', base_url('/capital_option/overview'));
    }

    public function customer()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('customer_staff_max_amount', '員工每季消費上限', 'required|integer|greater_than_equal_to[0]');

            if ($this->form_validation->run() !== FALSE) {
                $this->option_model
                    ->where('name', 'like', 'customer')
                    ->delete();

                $this->option_model->insert([
                    'name' => 'customer_staff_max_amount',
                    'value' => $this->input->post('customer_staff_max_amount'),
                ]);

                redirect(base_url('/capital_option/customer/'), 'refresh');
            }
        }

        $_options = $this->option_model
            ->where('name', 'like', 'customer')
            ->get_all();

        $options = [];
        if ($_options){
            foreach ($_options as $option){
                $options[$option['name']] = $option['value'];
            }
        }

        $data = [
            'options' => $options,
            'title' => '編輯消費者參數',
            'view' => 'capital/option/customer',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/views/supervisor/purchase.php
<div class="container">

    <h1 class="mb-4"><?=$retailer['company']?> 經銷商進貨明細</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">進貨單編號</th>
            <th class="text-center">訂貨日期</th>
            <th class="text-center">進貨日期</th>
            <th class="text-center">出貨單位</th>
            <th class="text-center">進貨金額</th>
            <th class="text-center"></th>
        </tr>
        <?php
        if ($purchases) {
            foreach ($purchases as $purchase) {
                ?>
                <tr>
                    <td class="text-center"><?= $purchase['purchaseNum'] ?></td>
                    <td class="text-center"><?= $purchase['created_at'] ?></td>
                    <td class="text-center"><?= $purchase['shipped_at'] ?></td>
                    <td class="text-center"><?= empty($purchase['shipout_retailer']) ? '' : $purchase['shipout_retailer']['company'] ?></td>
                    <td class="text-center">$<?= number_format($purchase['subtotal']) ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php if (!empty($authority['detail'])){ ?>
                                <a class="btn btn-info btn-sm"
                                   href="<?= base_url('/supervisor/detail/' . $purchase['id']) ?>">
                                    <i class="fas fa-search"></i> 詳細
                                </a>
                            <?php } ?>
                        </div>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="6" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>
</div><file_sep>/application/migrations/044_add_product_permission.php
<?php
//經銷商訂貨單產品
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_product_permission extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'product_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'include_retailers' => [
                'type' => 'VARCHAR',
                'constraint' => 255,
                'null' => TRUE,
            ],
            'remark' => [
                'type' => 'TEXT',
                'null' => TRUE,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_product_permissions');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_product_permissions');
    }
}<file_sep>/application/views/confirm/overview.php
<div class="container">

    <h1 class="mb-4">確認紀錄列表</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">日期</th>
            <th class="text-center">確認者名稱</th>
            <th class="text-center">結果</th>
            <th class="text-center">備註</th>
        </tr>
        <?php
        if ($confirms) {
            foreach ($confirms as $confirm) {
                ?>
                <tr>
                    <td class="text-center"><?= $confirm['created_at'] ?></td>
                    <td class="text-center"><?= $confirm['retailer']['company'] ?></td>
                    <td class="text-center"><?=confirmStatus($confirm['audit'])?></td>
                    <td class="text-center"><?=$confirm['memo']?></td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="4" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div><file_sep>/application/models/Purchase_shortage_model.php
<?php

class Purchase_shortage_model extends MY_Model
{
    public $table = 'olive_purchase_shortages';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
        $this->has_one['item'] = array('foreign_model' => 'Purchase_item_model', 'foreign_table' => 'olive_purchase_items', 'foreign_key' => 'id', 'local_key' => 'purchase_item_id');
        $this->has_one['expense'] = array('foreign_model' => 'Expense_model', 'foreign_table' => 'olive_expenses', 'foreign_key' => 'event_id', 'local_key' => 'id');
    }

    public function getTransferShortage($shortage_id, $isTransfer = false)
    {
        $transfer_purchase_id = '';
        if (!$isTransfer) {
            $shortage = $this
                ->with_purchase()
                ->with_item()
                ->get($shortage_id);
            if ($shortage && $shortage['purchase'] && $shortage['item'] && !is_null($shortage['purchase']['transfer_id'])) {
                $transfer_purchase_id = $shortage['purchase']['transfer_id'];
                $product_id = $shortage['item']['product_id'];
            }
        } else {
            $shortage = $this
                ->with_purchase(['with' => ['relation' => 'transfer_from']])
                ->with_item()
                ->get($shortage_id);
            if ($shortage && $shortage['purchase'] && $shortage['item'] && $shortage['purchase']['transfer_from']) {
                $transfer_purchase_id = $shortage['purchase']['transfer_from']['id'];
                $product_id = $shortage['item']['product_id'];
            }
        }

        if ($transfer_purchase_id) {
            $this->load->model('purchase_item_model');
            $transfer_purchase_item = $this->purchase_item_model->getPurchaseItemOfId($transfer_purchase_id, $product_id);

            if ($transfer_purchase_item && $transfer_purchase_item['shortage']) {
                return $transfer_purchase_item;
            }
        }

        return false;
    }
}

?>
<file_sep>/application/views/purchase/edit.php
<div class="container">
    <h1 class="mb-4 text-center">編輯進貨單</h1>

    <form method="post" id="purchaseForm">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group">
            <label class="font-weight-bold">進貨日期</label>
            <input type="date" name="created_at" class="form-control" value="<?= set_value('created_at', date('Y-m-d', strtotime($purchase['created_at']))) ?>" required/>
        </div>

        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th>項次</th>
                <th>貨品編號</th>
                <th>貨品名稱</th>
                <th>單價(含稅)</th>
                <th>訂購數量</th>
                <th>金額小計</th>
                <th>折扣</th>
                <th>折扣價</th>
            </tr>
            <?php if ($purchase['items']) {
                $i = 1;
                foreach ($purchase['items'] as $item) {
                    ?>
                    <tr<?= ($item['product']['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
                        <td class="text-center"><?= $i ?></td>
                        <td><?= $item['product']['p_num'] ?></td>
                        <td>
                            <?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?>
                        </td>
                        <td>
                            <input type="number" name="items[<?= $item['product_id'] ?>][price]" data-qty="<?= $item['qty'] ?>" min="0" required class="item_cash form-control text-right" value="<?=$item['price']?>" />
                        </td>
                        <td class="text-right"><?= $item['qty'] ?></td>
                        <td class="item_subtotal text-right">$<?= number_format($item['subtotal']) ?></td>
                        <td>
                            <div class="input-group">
                                <input type="number" name="items[<?= $item['product_id'] ?>][discount]" min="1" max="100" required class="item_discount form-control text-right" value="<?=$item['discount']?>" />
                                <div class="input-group-append">
                                    <span class="input-group-text">%</span>
                                </div>
                            </div>
                        </td>
                        <td>
                            <input type="number" name="items[<?= $item['product_id'] ?>][total]" min="0" required class="item_total form-control text-right" value="<?=$item['total']?>" />
                        </td>
                    </tr>
                    <?php
                    $i++;
                }
            }
            ?>
            <tr>
                <td colspan="6"></td>
                <td class="text-right font-weight-bold">總計</td>
                <td id="total_text" class="text-right font-weight-bold">$<?=number_format($purchase['total'])?></td>
            </tr>
        </table>

        <div class="form-group text-center">
            <a href="<?= base_url('/purchase/overview/') ?>" class="btn btn-secondary">取消</a>
            <input type="submit" class="btn btn-success" value="更新"/>
        </div>
    </form>
</div>

<script>
    $().ready(function () {
        $('#purchaseForm input.item_cash').change(function () {
            var price = parseInt($(this).val());
            var qty = parseInt($(this).data('qty'));
            var item = $(this).parents('tr');
            item.find('td.item_subtotal').text(numberWithCommas(price * qty));
            var discount = parseInt(item.find('.item_discount').val()) || 100;
            var discount_price = Math.floor(price * discount / 100) * qty;
            item.find('.item_total').val(discount_price);
            calc_total();
        });

        $('#purchaseForm input.item_discount').change(function () {
            var discount = parseInt($(this).val()) || 100;
            var item = $(this).parents('tr');
            var price = parseInt(item.find('.item_cash').val());
            var qty = parseInt(item.find('.item_cash').data('qty'));
            var discount_price = Math.floor(price * discount / 100) * qty;
            item.find('.item_total').val(discount_price);
            calc_total();
        });

        $('#purchaseForm input.item_total').change(function () {
            calc_total();
        });

        function calc_total() {
            var total = 0;
            $('#purchaseForm input.item_total').each(function () {
                total += parseInt($(this).val());
            });

            $('#total_text').text('$' + numberWithCommas(total));
        }
    });

    function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    $("#purchaseForm").keydown(function(e){
        if(e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    });
</script><file_sep>/application/controllers/Capital_privilege.php
<?php

class Capital_privilege extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('privilege_model');

        $this->session->set_userdata('return_page', base_url('/capital_privilege/overview'));
    }

    public function overview()
    {
        $this->config->load('class_list', true);
        $class_list = $this->config->item('class_list');

        $privileges = $this->privilege_model
            ->get_all();
        if ($privileges) {
            foreach ($privileges as $privilege) {
                if (!isset($class_list[$privilege['classname']])) {
                    $this->privilege_model->delete($privilege['id']);
                }
            }
        }

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_privilege', 'apps')){
            $authority['apps'] = true;
        }

        $data = [
            'class_list' => $class_list,
            'authority' => $authority,
            'title' => '權限總覽',
            'view' => 'capital/privilege/overview',
        ];

        $this->_preload($data);
    }

    public function apps($classname)
    {
        $this->config->load('class_list', true);
        $class_list = $this->config->item('class_list');

        if (!$classname || empty($class_list[$classname])) {
            show_error('頁面名稱錯誤');
        }

        $privileges = $this->privilege_model
            ->where('classname', $classname)
            ->get_all();

        if ($privileges) {
            foreach ($privileges as $privilege) {
                if (!isset($class_list[$classname]['method'][$privilege['methodname']])) {
                    $this->privilege_model->delete($privilege['id']);
                }
            }
        }

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_privilege', 'authority')){
            $authority['authority'] = true;
        }

        $data = [
            'classname' => $classname,
            'class_list' => $class_list,
            'authority' => $authority,
            'title' => '頁面權限總覽',
            'view' => 'capital/privilege/apps',
        ];

        $this->_preload($data);
    }

    public function authority($classname, $methodname)
    {
        $this->config->load('class_list', true);
        $class_list = $this->config->item('class_list');

        if (!$classname || empty($class_list[$classname])) {
            show_error('頁面名稱錯誤');
        }

        if (empty($class_list[$classname]['method'][$methodname])) {
            show_error('動作名稱錯誤');
        }

        $privilege = $this->privilege_model
            ->where('classname', $classname)
            ->where('methodname', $methodname)
            ->get();

        $rules = [];
        if ($privilege) {
            $rules = unserialize($privilege['rules']);
        }

        $permission = [
            0 => '禁止',
            1 => '允許',
        ];

        $this->load->model('retailer_group_model');
        $_groups = $this->retailer_group_model
            ->with_role()
            ->with_level_type()
            ->order_by('retailer_role_id')
            ->order_by('id')
            ->get_all();
        if (!$_groups){
            show_error('尚未設定群組');
        }
        $groups = [];
        foreach ($_groups as $group){
            if ($rules && isset($rules[$group['id']])){
                $group['permission'] = $rules[$group['id']];
            } else {
                $group['permission'] = 0;
            }
            $groups[$group['id']] = $group;
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('rules[]', '權限設定', 'required|integer|in_list[' . implode(',', array_keys($permission)) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $_rules = (array)$this->input->post('rules');
                $new_rules = [];
                if ($_rules){
                    foreach ($_rules as $group_id => $group_val){
                        if (in_array($group_id, array_keys($groups))){
                            $new_rules[$group_id] = $group_val;
                        }
                    }
                }

                if ($privilege) {
                    $this->privilege_model->update([
                        'rules' => serialize($new_rules),
                    ], ['id' => $privilege['id']]);
                } else {
                    $this->privilege_model->insert([
                        'classname' => $classname,
                        'methodname' => $methodname,
                        'rules' => serialize($new_rules),
                    ]);
                }

                redirect(base_url('/capital_privilege/apps/' . $classname));
            }
        }
        $data = [
            'classname' => $classname,
            'methodname' => $methodname,
            'class_list' => $class_list,
            'groups' => $groups,
            'permission' => $permission,
            'title' => '動作權限設定',
            'view' => 'capital/privilege/authority',
        ];

        $this->_preload($data);
    }
}<file_sep>/application/views/welcome.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4 text-center">歡迎 <?= $dealer['company'] ?></h1>
            <div class="card">
                <div class="card-header">基本資料</div>
                <div class="card-body">
                    <p class="card-text">帳號: <?= $dealer['account'] ?></p>
                    <p class="card-text">名字: <?= $dealer['name'] ?></p>
                    <p class="card-text">身份證字號/統一編號: <?= $dealer['identity'] ?></p>
                    <p class="card-text">性別: <?= $dealer['gender'] ? '男' : '女' ?></p>
                    <p class="card-text">聯絡電話1: <?= $dealer['phone'] ?></p>
                    <p class="card-text">聯絡電話2: <?= $dealer['altPhone'] ?></p>
                    <p class="card-text">送貨地址: <?= $dealer['address'] ?></p>
                    <?php if (!empty($dealer['sales_retailer'])) { ?>
                        <p class="card-text">輔銷單位: <?= $dealer['sales_retailer']['company'] ?></p>
                    <?php } ?>
                    <?php if (!empty($dealer['sales_dealer'])) { ?>
                        <p class="card-text">輔銷人: <?= $dealer['sales_dealer']['name'] ?></p>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
</div>
<file_sep>/application/models/Purchase_return_model.php
<?php

class Purchase_return_model extends MY_Model
{
    public $table = 'olive_purchase_returns';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
        $this->has_one['item'] = array('foreign_model' => 'Purchase_item_model', 'foreign_table' => 'olive_purchase_items', 'foreign_key' => 'id', 'local_key' => 'purchase_item_id');
        $this->has_one['expense'] = array('foreign_model' => 'Expense_model', 'foreign_table' => 'olive_expenses', 'foreign_key' => 'event_id', 'local_key' => 'id');
    }
}

?>
<file_sep>/application/views/consumer/edit.php
<div class="container">
    <h1 class="mb-4">編輯消費紀錄</h1>

    <form method="post">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group">
            <label class="font-weight-bold">訂單日期</label>
            <input type="date" name="created_at" class="form-control" value="<?= set_value('created_at', date('Y-m-d', strtotime($order['created_at']))) ?>" required/>
        </div>

        <div class="form-group d-flex justify-content-between">
            <a href="<?= base_url('/consumer/overview/') ?>" class="btn btn-secondary">取消</a>
            <input type="submit" class="btn btn-success" value="更新"/>
        </div>
    </form>
</div><file_sep>/application/models/Pao_model.php
<?php

class Pao_model extends MY_Model
{
    public $table = 'olive_paos';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';
    }

    public function getPaoSelect()
    {
        $_paos = $this->get_all();
        $paos = [];
        if ($_paos) {
            foreach ($_paos as $pao) {
                $paos[$pao['id']] = '有效期限' . $pao['expiration_month'] . '月(PAO: ' . $pao['pao_month'] . '月)';
            }
        }
        return $paos;
    }
}

?>
<file_sep>/application/controllers/Purchase.php
<?php

class Purchase extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged())) {
            redirect(base_url('/'));
        }

        $this->load->model('purchase_model');
        $this->load->model('purchase_item_model');
        $this->load->model('shipment_model');
        $this->load->model('shipment_item_model');
        $this->load->library('stock_lib');
        $this->load->library('purchase_lib');
        $this->load->helper('data_format');

        $this->session->set_userdata('return_page', base_url('/purchase/overview'));
    }

    public function overview()
    {
        $shipout_retailers = $this->purchase_lib->getShipOutList($this->dealer['retailer_id']);

        $search = array(
            'purchaseNum' => $this->input->get('purchaseNum'),
            'created_start' => $this->input->get('created_start'),
            'created_end' => $this->input->get('created_end'),
            'isConfirmed' => $this->input->get('isConfirmed'),
            'isPaid' => $this->input->get('isPaid'),
            'isShipped' => $this->input->get('isShipped'),
            'isReceived' => $this->input->get('isReceived'),
            'shipout_retailer_id' => (int)$this->input->get('shipout_retailer_id'),
        );

        if ($search['purchaseNum'] != ''){
            $this->purchase_model->where('purchaseNum', $search['purchaseNum']);
        }

        if ($search['created_start'] != ''){
            $this->purchase_model->where('created_at', '>=', $search['created_start']);
        }

        if ($search['created_end'] != ''){
            $this->purchase_model->where('created_at', '<=', date('Y-m-d', strtotime($search['created_end'] . " +1 days")));
        }

        if ($search['isConfirmed'] != ''){
            if ($search['isConfirmed'] == '-1'){
                $this->purchase_model->where('isConfirmed IS NULL', null, null, false, false, true);
            } else {
                $this->purchase_model->where('isConfirmed', $search['isConfirmed']);
            }
        }

        if ($search['isPaid'] != ''){
            $this->purchase_model->where('isPaid', $search['isPaid']);
        }

        if ($search['isShipped'] != ''){
            $this->purchase_model->where('isShipped', $search['isShipped']);
        }

        if ($search['isReceived'] != ''){
            if ($search['isReceived'] == 'isCorrect') {
                $this->purchase_model->where('isShipConfirmed', 1);
            } elseif ($search['isReceived'] == 'isRevised'){
                $this->purchase_model->where('isRevised', 1);
            } elseif ($search['isReceived'] == 'isReturn'){
                $this->purchase_model->where('isReturn', 1);
            } elseif ($search['isReceived'] == 'isAllowance'){
                $this->purchase_model->where('isAllowance', 1);
            }
        }

        if ($search['shipout_retailer_id'] != ''){
            $this->purchase_model->where('shipout_retailer_id', $search['shipout_retailer_id']);
        }

        $total_purchases_count = $this->purchase_model
            ->with_trashed()
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->count_rows();

        if ($search['purchaseNum'] != ''){
            $this->purchase_model->where('purchaseNum', $search['purchaseNum']);
        }

        if ($search['created_start'] != ''){
            $this->purchase_model->where('created_at', '>=', $search['created_start']);
        }

        if ($search['created_end'] != ''){
            $this->purchase_model->where('created_at', '<=', date('Y-m-d', strtotime($search['created_end'] . " +1 days")));
        }

        if ($search['isConfirmed'] != ''){
            if ($search['isConfirmed'] == '-1'){
                $this->purchase_model->where('isConfirmed IS NULL', null, null, false, false, true);
            } else {
                $this->purchase_model->where('isConfirmed', $search['isConfirmed']);
            }
        }

        if ($search['isPaid'] != ''){
            $this->purchase_model->where('isPaid', $search['isPaid']);
        }

        if ($search['isShipped'] != ''){
            $this->purchase_model->where('isShipped', $search['isShipped']);
        }

        if ($search['isReceived'] != ''){
            if ($search['isReceived'] == 'isCorrect') {
                $this->purchase_model->where('isShipConfirmed', 1);
            } elseif ($search['isReceived'] == 'isRevised'){
                $this->purchase_model->where('isRevised', 1);
            } elseif ($search['isReceived'] == 'isReturn'){
                $this->purchase_model->where('isReturn', 1);
            } elseif ($search['isReceived'] == 'isAllowance'){
                $this->purchase_model->where('isAllowance', 1);
            }
        }

        if ($search['shipout_retailer_id'] != ''){
            $this->purchase_model->where('shipout_retailer_id', $search['shipout_retailer_id']);
        }

        $purchases = $this->purchase_model
            ->with_trashed()
            ->with_transfer_from()
            ->with_retailer(['fields' => 'company'])
            ->with_shipin_retailer('fields:company')
            ->with_shipout_retailer('fields:company')
            ->with_items()
            ->with_order_transfer()
            ->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
            ->with_shipments(['non_exclusive_where' => "`ship_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='shipment'"]])
            ->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->order_by($this->purchase_model->get_table_name() . '.id', 'desc')
            ->paginate(20, $total_purchases_count);

        if ($purchases) {
            foreach ($purchases as $key => $purchase) {
                $purchase_lib = new purchase_lib($purchase);
                $purchases[$key]['paid_label'] = $purchase_lib->generatePaidLabel();
                $purchases[$key]['confirm_label'] = $purchase_lib->generateConfirmLabel();
                $purchases[$key]['shipped_label'] = $purchase_lib->generateShippedLabel();
            }
        }

        //權限設定
        $authority = array();
        if (!$this->dealer['disabled'] && $this->authentic->authority('purchase', 'add')){
            $authority['add'] = true;
        }
        if (!$this->dealer['disabled'] && $this->authentic->authority('purchase', 'add2')){
            $authority['add2'] = true;
        }
        if ($this->authentic->authority('purchase', 'detail')){
            $authority['detail'] = true;
        }
        if ($this->authentic->authority('purchase', 'detail2')){
            $authority['detail2'] = true;
        }
        if ($this->authentic->authority('purchase', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('purchase', 'cancel')){
            $authority['cancel'] = true;
        }
        if ($this->authentic->authority('payment', 'add')){
            $authority['payment_add'] = true;
        }
        if ($this->authentic->authority('shipment', 'confirm')){
            $authority['shipment_confirm'] = true;
        }
        if ($this->authentic->authority('shipment', 'return_add')){
            $authority['return_add'] = true;
        }
        if ($this->authentic->authority('shipment', 'allowance_add')){
            $authority['allowance_add'] = true;
        }

        $data = [
            'shipout_retailers' => $shipout_retailers,
            'search' => $search,
            'purchases' => $purchases,
            'pagination' => $this->purchase_model->all_pages,
            'authority' => $authority,
            'title' => '進貨單列表',
            'view' => 'purchase/overview',
        ];

        $this->_preload($data);
    }

    public function detail($purchase_id, $show_price = true)
    {
        $purchase = $this->purchase_model
            ->with_trashed()
            ->with_transfer_from()
            ->with_retailer('fields:company,invoice_title')
            ->with_shipin_retailer('fields:company,invoice_title')
            ->with_shipout_retailer('fields:company,invoice_title')
            ->with_order_transfer(['with' =>
                [
                    ['relation' => 'order', 'with' => ['contact']],
                    ['relation' => 'retailer'],
                    ['relation' => 'shipout_retailer'],
                ]
            ])
            ->with_items(['with' =>
                [
                    'relation' => 'product',
                    'with' => ['relation' => 'product_kind', 'fields' => 'ctName']
                ]
            ])
            ->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
            ->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->get($purchase_id);

        if (!$purchase_id || !$purchase) {
            show_error('查無進貨單資料');
        }

        $purchase_lib = new purchase_lib($purchase);
        $purchase['paid_label'] = $purchase_lib->generatePaidLabel(true);
        $purchase['confirm_label'] = $purchase_lib->generateConfirmLabel(true);
        $purchase['shipped_label'] = $purchase_lib->generateShippedLabel();
        $shipments = [];
        $allowance_payments = [];
        $total_allowance_payment = 0;

        if ($purchase['isShipped']) {
            $real_shipin_retailer = $purchase['shipin_retailer'];
            $real_shipout_retailer = $purchase['shipout_retailer'];
            if (!is_null($purchase['transfer_id'])){
                $transfer_to_purchase = $this->purchase_model
                    ->with_shipin_retailer('fields:company,invoice_title')
                    ->with_shipout_retailer('fields:company,invoice_title')
                    ->get($purchase['transfer_id']);
                if ($transfer_to_purchase){
                    $real_shipout_retailer = $transfer_to_purchase['shipout_retailer'];
                }
            }

            $this->load->model('payment_model');
            //銷貨折讓
            $payments = $this->payment_model
                ->with_paid_retailer('fields:company,invoice_title')
                ->with_received_retailer('fields:company,invoice_title')
                ->with_confirm(['non_exclusive_where' => "confirm_type='payment'"])
                ->where('pay_type', 'shipment_allowance')
                ->where('pay_id', $purchase_id)
                ->get_all();
            if ($payments) {
                foreach ($payments as $payment){
                    $payment['payment_confirm_label'] = $this->payment_model->generatePaymentConfirmLabel($payment, true);
                    $allowance_payments[] = $payment;

                    if ($payment['active'] && $payment['isConfirmed']) {
                        $total_allowance_payment += $payment['price'];
                    }
                }
            }

            $_shipments = $this->shipment_model
                ->with_expirations(['with' => ['relation' => 'product']])
                ->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
                ->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
                ->where('ship_type', 'purchase')
                ->where('ship_id', $purchase_id)
                ->order_by('id', 'asc')
                ->get_all();

            if ($_shipments){
                foreach ($_shipments as $shipment){
                    if ($shipment['shipin_retailer_id'] != $purchase['retailer_id']){
                        $shipment['isReturn'] = true;
                        $shipment['shipout_retailer'] = $real_shipin_retailer;
                        $shipment['shipin_retailer'] = $real_shipout_retailer;
                    } else {
                        $shipment['shipout_retailer'] = $real_shipout_retailer;
                        $shipment['shipin_retailer'] = $real_shipin_retailer;
                    }
                    $shipments[] = $shipment;

                    if (is_null($shipment['shipment_id'])) {
                        $revised = $this->shipment_model
                            ->with_expirations(['with' => ['relation' => 'product']])
                            ->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
                            ->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
                            ->where('shipment_id', $shipment['id'])
                            ->where('isConfirmed', 0)
                            ->order_by('id', 'asc')
                            ->get_all();

                        if ($revised) {
                            $revised['shipout_retailer'] = $real_shipout_retailer;
                            $revised['shipin_retailer'] = $real_shipin_retailer;

                            $shipments = array_merge($shipments, $revised);
                        }
                    }
                }

                if ($shipments){
                    foreach ( array_reverse($shipments) as $shipment ) {
                        if ($shipment['isConfirmed'] || !empty($shipment['isReturn'])) {
                            foreach ($shipment['expirations'] as $sitem) {
                                foreach ($purchase['items'] as $pkey => $pitem) {
                                    if ($sitem['product_id'] == $pitem['product_id']) {
                                        if (!isset($purchase['items'][$pkey]['shipping_qty'])){
                                            $purchase['items'][$pkey]['shipping_qty'] = 0;
                                        }
                                        if (!empty($shipment['isReturn'])){
                                            $purchase['items'][$pkey]['shipping_qty'] -= $sitem['qty'];
                                        } else {
                                            $purchase['items'][$pkey]['shipping_qty'] += $sitem['qty'];
                                        }
                                    }
                                }
                            }

                            if (empty($shipment['isReturn'])) {
                                break;
                            }
                        }
                    }
                }
            }
        }

        //權限設定
        $authority = array();
        if ($this->authentic->authority('shipment', 'revise_edit')){
            $authority['revise_edit'] = true;
        }
        if ($this->authentic->authority('payment', 'confirm')){
            $authority['payment_confirm'] = true;
        }

        $data = [
            'purchase' => $purchase,
            'shipments' => $shipments,
            'allowance_payments' => $allowance_payments,
            'total_allowance_payment' => $total_allowance_payment,
            'show_price' => $show_price,
            'authority' => $authority,
            'title' => '進貨單詳細資料',
            'view' => 'purchase/detail',
        ];

        $this->_preload($data);
    }

    //不能看到價格
    public function detail2($purchase_id)
    {
        $this->detail($purchase_id, false);
    }

    //不能看到價格
    public function add2($shipout_retailer_id = '', $shipin_retailer_id = '')
    {
        $this->add($shipout_retailer_id, $shipin_retailer_id, false);
    }

    public function add($shipout_retailer_id = '', $shipin_retailer_id = '', $show_price = true)
    {
        if ($this->dealer['disabled']){
            show_error('因進貨金額不到最低門檻，故已被取消經銷商資格且無法進貨，後續事宜請聯繫您的輔銷人！');
        }

        $this->load->model('retailer_model');
        $this->load->model('retailer_relationship_model');
        $this->load->model('product_relationship_model');
        $discount = 100;
        $products = [];
        $shipin_retailers = [];
        $invoice_retailers = [];
        $invoice_send_retailers = [];
        $shipout_retailers = $this->purchase_lib->getShipOutList($this->dealer['retailer_id']);

        if (count($shipout_retailers) == 1) {
            $shipout_retailer_id = current(array_keys($shipout_retailers));
        }

        if ($shipout_retailer_id && isset($shipout_retailers[$shipout_retailer_id])) {
            $shipout_retailer = $shipout_retailers[$shipout_retailer_id];
            $discount = $shipout_retailer['discount'];

            $shipin_retailers = $this->purchase_lib->getShipInList($this->dealer['retailer_id'], $shipout_retailer_id);

            if (count($shipin_retailers) == 1) {
                $shipin_retailer_id = current(array_keys($shipin_retailers));
            }

            if ($shipin_retailer_id) {
                $shipin_retailer = $shipin_retailers[$shipin_retailer_id];

                $invoice_retailers = $this->purchase_lib->getInvoiceList($this->dealer['retailer_id'], $shipout_retailer_id);
                $invoice_send_retailers = $this->purchase_lib->getInvoiceSendList($this->dealer['retailer_id']);

                if ($shipin_retailer_id != $this->dealer['retailer_id']){
                    //取得產品折扣值
                    $relationship_products = $this->product_relationship_model->getRelationshipProducts($shipin_retailer_id, $this->dealer['retailer_id']);
                } else {
                    //取得產品折扣值
                    $relationship_products = $this->product_relationship_model->getRelationshipProducts($this->dealer['retailer_id'], $shipout_retailer_id);
                }

                $this->load->model('product_model');
                $this->load->model('product_permission_model');
                $this->load->model('stock_model');
                $products = $this->product_permission_model->getPermissionProducts($this->dealer['retailer_id']);
                $stock_table = $this->stock_model->get_table_name();

                foreach ($products as $product_id => $product) {
                    $products[$product_id]['discount'] = empty($relationship_products[$product_id]) ? null : $relationship_products[$product_id];
                }

                if ($shipout_retailer['hasStock'] || $shipin_retailer['hasStock']) {
                    $enableStep = (!empty($this->dealer['isAllowBulk'])) ? false : true;

                    foreach ($products as $product_id => $product) {
                        $products[$product_id]['step'] = $enableStep ? $product['boxAmount'] : 1;
                        if ($shipin_retailer['hasStock']) {
                            $stock = $this->stock_model
                                ->fields('SUM(' . $stock_table . '.stock) as active_total')
                                ->where('product_id', $product_id)
                                ->where('retailer_id', $shipin_retailer_id)
                                ->where('stock', '>', 0)
                                ->group_start()
                                ->where('expired_at', '>=', date('Y-m-d'), true)
                                ->where('expired_at IS NULL', null, null, true, false, true)
                                ->group_end()
                                ->order_by('ISNULL(expired_at)', 'asc')
                                ->order_by('expired_at', 'asc')
                                ->get();

                            $products[$product_id]['stock']['shipin'] = $stock['active_total'];
                        }

                        if ($shipout_retailer['hasStock']) {
                            $stock = $this->stock_model
                                ->fields('SUM(' . $stock_table . '.stock) as active_total')
                                ->where('product_id', $product_id)
                                ->where('retailer_id', $shipout_retailer_id)
                                ->where('stock', '>', 0)
                                ->group_start()
                                ->where('expired_at', '>=', date('Y-m-d'), true)
                                ->where('expired_at IS NULL', null, null, true, false, true)
                                ->group_end()
                                ->order_by('ISNULL(expired_at)', 'asc')
                                ->order_by('expired_at', 'asc')
                                ->get();

                            if ($stock && $product['boxAmount'] <= $stock['active_total']) {
                                $products[$product_id]['stock']['shipout'] = $stock['active_total'];
                                $products[$product_id]['box_max'] = ceil($stock['active_total'] / $product['boxAmount']);
                            } else {
                                $products[$product_id]['stock']['shipout'] = 0;
                            }
                        }
                    }
                }

                if ($this->input->post()) {
                    $this->form_validation->set_rules('retailer_address', '進貨地址', 'required|max_length[200]');
                    $this->form_validation->set_rules('shipin_address', '收貨地址', 'required|max_length[200]');

                    if (!empty($_POST['isInvoice'])) {
                        $this->form_validation->set_rules('invoice_retailer_id', '發票對象', 'integer|in_list[' . implode(',', array_keys($invoice_retailers)) . ']');
                        $this->form_validation->set_rules('invoice_retailer', '發票對象', 'required|max_length[200]');
                        $this->form_validation->set_rules('invoice_send_retailer_id', '發票寄送對象', 'integer|in_list[' . implode(',', array_keys($invoice_send_retailers)) . ']');
                        $this->form_validation->set_rules('invoice_send_retailer', '發票寄送對象', 'required|max_length[200]');
                        $this->form_validation->set_rules('invoice_send_address', '發票寄送地址', 'required|max_length[200]');
                    }

                    $this->form_validation->set_rules('items[][qty]', '訂購數量', 'callback_check_total[' . json_encode(['products' => $products, 'items' => $this->input->post('items')]) . ']');

                    if ($this->form_validation->run() !== FALSE) {
                        $purchaseSerialNum = $this->purchase_model->getNextPurchaseSerialNum();

                        //收貨對象與進貨單位不同
                        if ($shipin_retailer_id != $this->dealer['retailer_id']){
                            $new_retailer_id = $shipin_retailer_id;
                            $new_retailer_address = $this->input->post('shipin_address');
                            $new_shipout_retailer_id = $this->dealer['retailer_id'];

                            if (!empty($_POST['isInvoice'])) {
                                $relative_invoice_retailer = $this->retailer_relationship_model
                                    ->where('relation_type', 'invoice')
                                    ->where('retailer_id', $new_retailer_id)
                                    ->where('relation_retailer_id', $new_shipout_retailer_id)
                                    ->where('alter_retailer_id', $new_retailer_id)
                                    ->get();
                                if ($relative_invoice_retailer){
                                    if ($relative_invoice_retailer['discount']){
                                        $discount = $relative_invoice_retailer['discount'];
                                    }
                                }
                            }
                        } else {
                            $new_retailer_id = $this->dealer['retailer_id'];
                            $new_retailer_address = $this->input->post('retailer_address');
                            $new_shipout_retailer_id = $shipout_retailer_id;

                            if (!empty($_POST['isInvoice']) && !empty($invoice_retailers[$this->input->post('invoice_retailer_id')]['discount'])) {
                                $discount = $invoice_retailers[$this->input->post('invoice_retailer_id')]['discount'];
                            }
                        }

                        $insert_data = [
                            'retailer_id' => $new_retailer_id,
                            'retailer_address' => $new_retailer_address,
                            'shipout_retailer_id' => $new_shipout_retailer_id,
                            'shipin_retailer_id' => $shipin_retailer_id,
                            'shipin_address' => $this->input->post('shipin_address'),
                            'serialNum' => $purchaseSerialNum,
                            'purchaseNum' => date('Ym') . $purchaseSerialNum,
                            'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
                            'isInvoice' => empty($_POST['isInvoice']) ? 0 : 1,
                            'dealer_id' => $this->dealer['id'],
                        ];

                        if (!empty($_POST['isInvoice'])) {
                            $insert_data['invoice_retailer'] = $this->input->post('invoice_retailer');
                            $insert_data['invoice_send_retailer'] = $this->input->post('invoice_send_retailer');
                            $insert_data['invoice_send_address'] = $this->input->post('invoice_send_address');
                        }

                        $purchase_id = $this->purchase_model->insert($insert_data);

                        $subtotal = 0;
                        $total = 0;

                        $items = (array)$this->input->post('items');

                        $isMatchBox = false;
                        foreach ($items as $product_id => $item) {
                            $qty = $item['qty'];
                            if ($qty > 0) {
                                $price = $products[$product_id]['pdCash'];
                                $item_discount = empty($relationship_products[$product_id]) ? $discount : $relationship_products[$product_id];
                                $item_subtotal = $price * $qty;
                                $item_total = floor($price * $item_discount / 100) * $qty;

                                $this->purchase_item_model->insert([
                                    'purchase_id' => $purchase_id,
                                    'product_id' => $product_id,
                                    'price' => $price,
                                    'qty' => $qty,
                                    'subtotal' => $price * $qty,
                                    'discount' => $item_discount,
                                    'total' => $item_total,
                                ]);

                                if ($item['qty'] % $products[$product_id]['boxAmount'] == 0) {
                                    $isMatchBox = true;
                                }

                                $subtotal += $item_subtotal;
                                $total += $item_total;
                            }
                        }

                        $this->purchase_model->update([
                            'isMatchBox' => $isMatchBox,
                            'subtotal' => $subtotal,
                            'total' => $total,
                        ], ['id' => $purchase_id]);

                        $this->load->model('payment_model');

                        $this->payment_model->insert([
                            'pay_type' => 'purchase',
                            'pay_id' => $purchase_id,
                            'paid_retailer_id' => $new_retailer_id,
                            'received_retailer_id' => $new_shipout_retailer_id,
                            'price' => $total,
                            'retailer_id' => $this->dealer['retailer_id'],
                            'dealer_id' => $this->dealer['id'],
                            'active' => 0,
                        ]);

                        //收貨對象與進貨單位不同
                        if ($shipin_retailer_id != $this->dealer['retailer_id']){
                            //目前使用者單位向出貨單位採購
                            $new_purchase_id = $this->purchase_model->transfer_purchase($purchase_id, $shipout_retailer_id, $this->dealer);
                            if ($new_purchase_id){
                                if ($show_price) {
                                    redirect(base_url('/purchase/detail/' . $new_purchase_id));
                                } else {
                                    redirect(base_url('/purchase/detail2/' . $new_purchase_id));
                                }
                            }
                        }

                        if ($show_price) {
                            redirect(base_url('/purchase/detail/' . $purchase_id));
                        } else {
                            redirect(base_url('/purchase/detail2/' . $purchase_id));
                        }

                    }
                }
            }
        }

        $this->load->helper('form');

        $data = [
            'shipin_retailer_id' => $shipin_retailer_id,
            'shipin_retailers' => $shipin_retailers,
            'shipout_retailer_id' => $shipout_retailer_id,
            'shipout_retailers' => $shipout_retailers,
            'invoice_retailers' => $invoice_retailers,
            'invoice_send_retailers' => $invoice_send_retailers,
            'products' => $products,
            'discount' => $discount,
            'show_price' => $show_price,
            'purchase_url' => $show_price ? base_url('purchase/add/') : base_url('purchase/add2/'),
            'title' => '新增進貨單',
            'view' => 'purchase/add',
        ];

        $this->_preload($data);
    }

    public function check_total($i, $params)
    {
        $params = json_decode($params, true);

        $products = $params['products'];
        $items = $params['items'];
        $totalQty = 0;
        $subtotal = 0;
        $error = '';

        foreach ($items as $product_id => $item) {
            if (!isset($products[$product_id])) {
                $error = '輸入的貨品有誤';
                break;
            }

            if ($item['qty'] % $products[$product_id]['step']){
                $error = '輸入的貨品數量必須為包裝數量倍數';
                break;
            }

            $subtotal += $item['qty'] * $products[$product_id]['pdCash'];
            $totalQty += intval($item['qty']);
        }

        if (!$totalQty) {
            $error = '您尚未選購商品';
        }

        if (!$error) {
            return true;
        } else {
            $this->form_validation->set_message('check_total', $error);
            return false;
        }
    }

    public function edit($purchase_id)
    {
        $purchase = $this->purchase_model
            ->with_items(['with' =>
                [
                    'relation' => 'product',
                ]
            ])
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->get($purchase_id);

        if (!$purchase_id || !$purchase) {
            show_error('查無進貨單資料！');
        }

        if ($purchase['isConfirmed']){
            show_error('此進貨單已確認');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('created_at', '進貨日期', 'required|valid_date');
            if ($this->form_validation->run() !== FALSE) {
                $items = (array)$this->input->post('items');

                $subtotal = 0;
                $total = 0;

                foreach ($purchase['items'] as $i) {
                    $product_id = $i['product_id'];
                    $qty = $i['qty'];
                    $price = $items[$product_id]['price'];
                    $discount = $items[$product_id]['discount'];
                    $item_subtotal = $price * $qty;
                    $item_total = floor($price * $discount / 100) * $qty;

                    $this->purchase_item_model->update([
                        'price' => $price,
                        'subtotal' => $item_subtotal,
                        'discount' => $discount,
                        'total' => $item_total,
                    ], ['id' => $i['id']]);

                    $subtotal += $item_subtotal;
                    $total += $item_total;
                }

                $this->purchase_model->update([
                    'subtotal' => $subtotal,
                    'total' => $total,
                    'created_at' => $this->input->post('created_at'),
                ], ['id' => $purchase_id]);

                $this->load->model('payment_model');

                $payments = $this->payment_model
                    ->where('pay_type', 'purchase')
                    ->where('pay_id', $purchase_id)
                    ->get_all();
                if ($payments) {
                    foreach ($payments as $payment) {
                        $this->payment_model->update([
                            'price' => $total,
                        ], ['id' => $payment['id']]);
                    }
                }

                redirect(base_url('/purchase/detail/' . $purchase_id));
            }
        }

        $data = [
            'purchase' => $purchase,
            'title' => '編輯進貨單',
            'view' => 'purchase/edit',
        ];

        $this->_preload($data);
    }

    public function cancel($purchase_id)
    {
        $purchase = $this->purchase_model
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->get($purchase_id);

        if (!$purchase_id || !$purchase) {
            show_error('查無進貨單資料！');
        }

        if ($purchase['isShipped']) {
            show_error('進貨單已經出貨不能取消');
        }

        $this->purchase_model->delete($purchase_id);

        $this->purchase_model->update([
            'transfer_id' => null,
        ], ['transfer_id' => $purchase_id]);

        $this->load->model('payment_model');
        $this->payment_model
            ->where('pay_type', 'purchase')
            ->where('pay_id', $purchase_id)
            ->where('active', 0)
            ->delete();

        redirect(base_url('/purchase/overview'));
    }
}

?><file_sep>/application/migrations/059_update_stock_counting_expiry_date.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_stock_counting_expiry_date extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_column('olive_stock_counting_items', [
            'expired_at' => [
                'type' => 'date',
                'null' => TRUE,
                'after' => 'stock',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_stock_counting_items', 'expired_at');
    }
}<file_sep>/application/libraries/Stock_lib.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Stock_lib
{
    var $CI;

    public function __construct()
    {
        $this->CI =& get_instance();

        $this->CI->load->model('product_model');
        $this->CI->load->model('stock_model');
    }

    //直接調整經銷商產品庫存
    public function retailer_adjust_stock($retailer_id, $product_id, $qty, $date = null)
    {
        $retailer = $this->getRetailer($retailer_id);
        if (!$retailer) return false;

        if ($this->isChange_retailer_stock($retailer)) {
            $this->adjust_retailer_stock($retailer_id, $product_id, $qty, $date);
        }
        return true;
    }

    //出貨確定時事件
    public function shipout_confirm($shipment_id)
    {
        $shipment = $this->getShipment($shipment_id);
        if (!$shipment) return false;

        $retailer_id = $shipment['shipout_retailer_id'];
        if (!empty($shipment['expirations'])) {
            foreach ($shipment['expirations'] as $expiration) {
                if ($this->isChange_retailer_stock($shipment['shipout_retailer'])) {
                    $this->adjust_retailer_stock($retailer_id, $expiration['product_id'], ($expiration['qty'] * -1), $expiration['expired_at']);
                }
            }
        }
        return true;
    }

    //出貨取消時事件
    public function shipout_rollback($shipment_id)
    {
        $shipment = $this->getShipment($shipment_id);
        if (!$shipment) return false;

        $retailer_id = $shipment['shipout_retailer_id'];
        if (!empty($shipment['expirations'])) {
            foreach ($shipment['expirations'] as $expiration) {
                if ($this->isChange_retailer_stock($shipment['shipout_retailer'])) {
                    $this->adjust_retailer_stock($retailer_id, $expiration['product_id'], $expiration['qty'], $expiration['expired_at']);
                }
            }
        }
        return true;
    }

    //收貨確定時事件
    public function shipin_confirm($shipment_id)
    {
        $shipment = $this->getShipment($shipment_id);
        if (!$shipment) return false;

        $retailer_id = $shipment['shipin_retailer_id'];
        if (!empty($shipment['expirations'])) {
            foreach ($shipment['expirations'] as $expiration) {
                if ($this->isChange_retailer_stock($shipment['shipin_retailer'])) {
                    $this->adjust_retailer_stock($retailer_id, $expiration['product_id'], $expiration['qty'], $expiration['expired_at']);
                }
            }
        }
        return true;
    }

    //收貨取消時事件
    public function shipin_rollback($shipment_id)
    {
        $shipment = $this->getShipment($shipment_id);
        if (!$shipment) return false;

        $retailer_id = $shipment['shipin_retailer_id'];
        if (!empty($shipment['expirations'])) {
            foreach ($shipment['expirations'] as $expiration) {
                if ($this->isChange_retailer_stock($shipment['shipin_retailer'])) {
                    $this->adjust_retailer_stock($retailer_id, $expiration['product_id'], ($expiration['qty'] * -1), $expiration['expired_at']);
                }
            }
        }
        return true;
    }

    public function getShipment($shipment_id)
    {
        $this->CI->load->model('shipment_model');
        return $this->CI->shipment_model
            ->with_shipout_retailer()
            ->with_shipin_retailer()
            ->with_expirations()
            ->get($shipment_id);
    }

    public function getRetailer($retailer_id)
    {
        $this->CI->load->model('retailer_model');
        return $this->CI->retailer_model
            ->get($retailer_id);
    }

    //檢查進出貨單位是否有計算庫存
    public function isChange_retailer_stock($shipment_retailer)
    {
        if (!empty($shipment_retailer) && $shipment_retailer['hasStock']){
            return true;
        }
        return false;
    }

    //檢查進出貨單位是否會計算總庫存
    public function isChange_total_stock($shipment_retailer)
    {
        if (!empty($shipment_retailer) && $shipment_retailer['totalStock']){
            return true;
        }
        return false;
    }

    //單位庫存調整數量，qty可負數
    public function adjust_retailer_stock($retailer_id, $product_id, $qty, $date = null)
    {
        if (!$retailer_id || !$product_id){
            return false;
        }

        $qty = intval($qty);
        if ($date){
            $this->CI->stock_model->where('expired_at', $date);
        } else {
            $this->CI->stock_model->where('expired_at IS NULL', null, null, false, false, true);
        }

        $stock = $this->CI->stock_model
            ->where('retailer_id', $retailer_id)
            ->where('product_id', $product_id)
            ->get();

        if ($stock) {
            $qty = $stock['stock'] + $qty;

            $this->CI->stock_model->update(
                [
                    'stock' => $qty
                ],
                ['id' => $stock['id']]
            );
        } else {
            $this->CI->stock_model->insert([
                'retailer_id' => $retailer_id,
                'product_id' => $product_id,
                'stock' => $qty,
                'expired_at' => $date,
            ]);
        }

        return true;
    }

    //直接給單位庫存數量
    public function retailer_stock_value($retailer_id, $product_id, $qty, $date = null)
    {
        if (!$retailer_id || !$product_id){
            return false;
        }

        $qty = intval($qty);
        if ($date){
            $this->CI->stock_model->where('expired_at', $date);
        } else {
            $this->CI->stock_model->where('expired_at IS NULL', null, null, false, false, true);
        }

        $stock = $this->CI->stock_model
            ->where('retailer_id', $retailer_id)
            ->where('product_id', $product_id)
            ->get();
        if ($stock) {
            $this->CI->stock_model->update([
                    'stock' => $qty
                ], ['id' => $stock['id']]);
        } else {
            $this->CI->stock_model->insert([
                'retailer_id' => $retailer_id,
                'product_id' => $product_id,
                'stock' => $qty,
                'expired_at' => $date,
            ]);
        }

        return true;
    }
}

?><file_sep>/application/models/Bad_login_model.php
<?php
class Bad_login_model extends MY_Model{
    public $table = 'bad_login';
    public $primary_key = 'autoid';

    function __construct(){
        parent::__construct();

        $this->timestamps = false;
        $this->return_as = 'array';
    }
}
?>
<file_sep>/application/migrations/019_add_expense.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_expense extends CI_Migration
{
    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'event_type' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => TRUE,
            ],
            'event_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'expense_type' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => TRUE,
            ],
            'price' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'dealer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_expenses');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_expenses');
    }
}<file_sep>/application/models/Stock_counting_item_model.php
<?php

class Stock_counting_item_model extends MY_Model
{
    public $table = 'olive_stock_counting_items';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['stock_counting'] = array('foreign_model' => 'Stock_counting_model', 'foreign_table' => 'olive_stock_countings', 'foreign_key' => 'id', 'local_key' => 'stock_counting_id');
        $this->has_one['product'] = array('foreign_model' => 'Product_model', 'foreign_table' => 'product', 'foreign_key' => 'pdId', 'local_key' => 'product_id');
    }
}

?>
<file_sep>/application/views/capital/relationship/invoice/add.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">新增發票關係單位</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>出貨單位</label>
                    <?php
                    echo form_dropdown('relation_retailer_id', ['' => ''] + $retailer_selects, set_value('relation_retailer_id'), 'class="form-control required"');
                    ?>
                </div>

                <div class="form-group">
                    <label>發票單位</label>
                    <?php
                    echo form_dropdown('alter_retailer_id', ['' => ''] + $retailer_selects, set_value('alter_retailer_id'), 'class="form-control required"');
                    ?>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">折扣</label>
                    <div class="input-group">
                        <input type="number" name="discount" class="form-control text-right" max="100" min="1" value="<?= set_value('discount') ?>"/>
                        <div class="input-group-append">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/capital_relationship_invoice/overview/' . $retailer['id'])?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="新增"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/purchase/add.php
<div class="container">
    <h1 class="mb-4 text-center">新增進貨單</h1>

    <form method="post" id="purchaseForm">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group row">
            <label class="col-sm-2 col-form-label font-weight-bold">訂貨日期</label>
            <div class="col-sm-10">
                <input readonly class="form-control-plaintext" value="<?= date('Y-m-d') ?>">
            </div>
        </div>

        <div class="form-group row">
            <label class="col-sm-2 col-form-label font-weight-bold">出貨單位</label>
            <div class="col-sm-10">
                <?php if (count($shipout_retailers) == 1) { ?>
                    <?= current($shipout_retailers)['company'] ?>
                    <input type="hidden" id="shipout_retailer_id" value="<?= $shipout_retailer_id ?>"/>
                <?php } else { ?>
                    <select id="shipout_retailer_id" name="shipout_retailer_id" class="form-control">
                        <option value=""></option>
                        <?php foreach ($shipout_retailers as $retailer_id => $retailer) { ?>
                            <option value="<?= $retailer_id ?>" <?php if (!empty($shipout_retailer_id) && $retailer_id == $shipout_retailer_id) {
                                echo 'selected';
                            } ?>><?= $retailer['company'] ?></option>
                        <?php } ?>
                    </select>
                <?php } ?>
            </div>
        </div>

        <div class="form-group row">
            <label class="col-sm-2 col-form-label font-weight-bold">進貨單位</label>
            <div class="col-sm-10">
                <?= $dealer['company'] ?>
                <input type="hidden" id="retailer_id" value="<?=$dealer['retailer_id']?>" />
            </div>
        </div>

        <div class="form-group row">
            <label class="col-sm-2 col-form-label font-weight-bold">進貨單位地址</label>
            <div class="col-sm-10">
                <input name="retailer_address" class="form-control" value="<?= $dealer['address'] ?>" required placeholder="自行輸入進貨單位地址" />
            </div>
        </div>

        <?php if (!empty($shipout_retailer_id)) { ?>
            <?php if ($shipin_retailers){ ?>
            <div class="form-group row">
                <label class="col-sm-2 col-form-label font-weight-bold">收貨對象</label>
                <div class="col-sm-10">
                    <?php if (count($shipin_retailers) == 1) { ?>
                        <?= current($shipin_retailers)['invoice_title'] ?>
                        <input type="hidden" id="shipin_retailer_id" value="<?= $shipin_retailer_id ?>"/>
                    <?php } else { ?>
                        <select id="shipin_retailer_id" name="shipin_retailer_id" class="form-control" required>
                            <option value=""></option>
                            <?php foreach ($shipin_retailers as $retailer_id => $retailer) { ?>
                                <option value="<?= $retailer_id ?>" data-address="<?= $retailer['address'] ?>" <?php if (!empty($shipin_retailer_id) && $retailer_id == $shipin_retailer_id) {
                                    echo 'selected';
                                } ?>><?= $retailer['invoice_title'] ?></option>
                            <?php } ?>
                        </select>
                    <?php } ?>
                </div>
            </div>
            <?php } ?>

            <?php if (!empty($shipin_retailer_id)) { ?>
                <div class="form-group row">
                    <label class="col-sm-2 col-form-label font-weight-bold">收貨地址</label>
                    <div class="col-sm-10">
                        <input name="shipin_address" class="form-control" value="<?= $shipin_retailers[$shipin_retailer_id]['address'] ?>" required placeholder="自行輸入收貨地址" />
                    </div>
                </div>


                <?php if ($shipin_retailer_id != 2 || $shipout_retailer_id != 1) { ?>
                    <div class="form-group row">
                        <label class="col-sm-2 col-form-label font-weight-bold">開立發票</label>
                        <div class="col-sm-10">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="checkbox" name="isInvoice" id="isInvoice"
                                       value="1">
                                <label class="form-check-label" for="isInvoice">需開立發票</label>
                            </div>
                        </div>
                    </div>
                <?php } else { ?>
                    <input type="hidden" name="isInvoice" value="1">
                <?php } ?>

                <?php if ($invoice_retailers){ ?>
                    <div id="invoice_container" class="<?php if ($shipin_retailer_id != 2 || $shipout_retailer_id != 1){ echo 'd-none';} ?>">
                        <div class="form-group row">
                            <label class="col-sm-2 col-form-label font-weight-bold">發票對象</label>
                            <div class="col-sm-10">
                                <div class="input-group">
                                    <select id="invoice_retailer_id" name="invoice_retailer_id" class="form-control">
                                        <option value="">自行輸入</option>
                                        <?php foreach ($invoice_retailers as $retailer_id => $retailer) { ?>
                                            <option value="<?= $retailer_id ?>" data-discount="<?= $retailer['discount'] ?>" <?php if ($retailer_id == $shipin_retailer_id){ echo 'selected'; } ?>><?= $retailer['invoice_title'] ?></option>
                                        <?php } ?>
                                    </select>
                                    <input id="invoice_retailer" name="invoice_retailer" class="form-control <?php if ($invoice_retailers) { echo 'd-none'; } ?>" required value="<?=$shipin_retailers[$shipin_retailer_id]['invoice_title']?>" placeholder="自行輸入發票對象" />
                                </div>
                            </div>
                        </div>

                        <div class="form-group row">
                            <label class="col-sm-2 col-form-label font-weight-bold">發票寄送對象</label>
                            <div class="col-sm-10">
                                <div class="input-group">
                                    <select id="invoice_send_retailer_id" name="invoice_send_retailer_id" class="form-control">
                                        <option value="">自行輸入</option>
                                        <?php foreach ($invoice_send_retailers as $retailer_id => $retailer) { ?>
                                            <option value="<?= $retailer_id ?>" data-address="<?= $retailer['address'] ?>" <?php if ($retailer_id == $shipin_retailer_id){ echo 'selected'; } ?>><?= $retailer['invoice_title'] ?></option>
                                        <?php } ?>
                                    </select>
                                    <input id="invoice_send_retailer" name="invoice_send_retailer" class="form-control  <?php if ($invoice_send_retailers) { echo 'd-none'; } ?>" required value="<?=$shipin_retailers[$shipin_retailer_id]['invoice_title']?>" placeholder="自行輸入發票寄送對象" />
                                </div>
                            </div>
                        </div>

                        <div class="form-group row">
                            <label class="col-sm-2 col-form-label font-weight-bold">發票寄送地址</label>
                            <div class="col-sm-10">
                                <input id="invoice_send_address" name="invoice_send_address" class="form-control" value="<?=$shipin_retailers[$shipin_retailer_id]['address']?>" required placeholder="自行輸入發票寄送地址" />
                            </div>
                        </div>
                    </div>
                <?php } ?>

                <div class="form-group row">
                    <label class="col-sm-2 col-form-label font-weight-bold">進貨方之備註</label>
                    <div class="col-sm-10">
                        <textarea rows="4" name="memo" class="form-control"><?= set_value('memo') ?></textarea>
                    </div>
                </div>

                <table class="table table-hover table-bordered table-responsive-sm">
                    <tr>
                        <th>項次</th>
                        <th>貨品編號</th>
                        <th>貨品名稱</th>
                        <?php if ($shipout_retailers[$shipout_retailer_id]['hasStock']) { ?>
                            <th>出貨單位庫存</th>
                        <?php } ?>
                        <?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
                            <th>進貨單位庫存</th>
                        <?php } ?>
                        <th>單價(含稅)</th>
                        <th>包裝數量</th>
                        <th>訂購數量</th>
                        <?php if ($show_price){ ?>
                        <th>金額小計</th>
                        <th>折扣</th>
                        <th>折扣價</th>
                        <?php } ?>
                        <?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
                            <th>進貨單位新庫存量</th>
                        <?php } ?>
                    </tr>
                    <?php if ($products) {
                        $i = 1;
                        foreach ($products as $product_id => $product) {
                            ?>
                            <tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
                                <td class="text-center"><?= $i ?></td>
                                <td><?= $product['p_num'] ?></td>
                                <td>
                                    <?= $product['pdName'] ?> <?= $product['intro2'] ?>
                                    <?php if ($product['picture']) { ?>
                                        <a class="show_picture" data-toggle="tooltip"
                                           title="<img src='<?= $product['picture'] ?>' />">
                                            <i class="far fa-images"></i>
                                        </a>
                                    <?php } ?>
                                </td>
                                <?php if ($shipout_retailers[$shipout_retailer_id]['hasStock']) { ?>
                                    <td class="text-right"><?= $product['stock']['shipout'] ?></td>
                                <?php } ?>
                                <?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
                                    <td class="text-right"><?= $product['stock']['shipin'] ?></td>
                                <?php } ?>
                                <td class="item_cash text-right">$<?= number_format($product['pdCash']) ?></td>
                                <td class="text-right"><?= $product['boxAmount'] ?></td>
                                <td>
                                    <input type="number" name="items[<?= $product_id ?>][qty]"
                                           min="0" class="itemQty form-control text-right"
                                        <?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
                                            data-shipin-stock="<?= intval($product['stock']['shipin']) ?>"
                                        <?php } ?>
                                           data-boxamount="<?= intval($product['boxAmount']) ?>"
                                           data-price="<?= intval($product['pdCash']) ?>"
                                           data-discount="<?= intval($product['discount']) ?>"
                                           step="<?= $product['step'] ?>"
                                           value="<?= set_value('items[' . $product_id . '][qty]') ?>"
                                           style="width: 120px;"
                                    />
                                </td>
                                <?php if ($show_price){ ?>
                                <td class="item_subtotal text-right"></td>
                                <td class="item_discount text-right"></td>
                                <td class="item_total text-right"></td>
                                <?php } ?>
                                <?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
                                    <td class="item_stock text-right"></td>
                                <?php } ?>
                            </tr>
                            <?php
                            $i++;
                        }
                    }
                    ?>
                    <tr>
                        <td colspan="3"></td>
                        <?php if ($shipout_retailers[$shipout_retailer_id]['hasStock']) { ?>
                            <td></td>
                        <?php } ?>
                        <?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
                            <td></td>
                        <?php } ?>
                        <td colspan="2" class="text-right font-weight-bold">小計</td>
                        <td id="total_qty_text" class="text-right font-weight-bold"></td>
                        <?php if ($show_price){ ?>
                        <td id="total_subtotal_text" class="text-right font-weight-bold"></td>
                        <td></td>
                        <td id="total_text" class="text-right font-weight-bold"></td>
                        <?php } ?>
                        <?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
                            <td id="total_stock_text" class="text-right font-weight-bold"></td>
                        <?php } ?>
                    </tr>
                    <tr>
                        <td colspan="3"></td>
                        <?php if ($shipout_retailers[$shipout_retailer_id]['hasStock']) { ?>
                            <td></td>
                        <?php } ?>
                        <?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
                            <td></td>
                        <?php } ?>
                        <td colspan="7"></td>
                    </tr>
                </table>
                <div class="form-group text-center">
                    <input type="submit" class="btn btn-success" value="送出進貨單" />
                    <input type="hidden" id="shipout_hasStock" value="<?= $shipout_retailers[$shipout_retailer_id]['hasStock'] ?>" />
                    <input type="hidden" id="shipin_hasStock" value="<?= $shipin_retailers[$shipin_retailer_id]['hasStock'] ?>" />
                    <input type="hidden" id="totalQty" value="0" />
                    <input type="hidden" id="subtotal" value="0" />
                    <input type="hidden" id="discount" value="<?=$discount?>" />
                </div>
            <?php } ?>
        <?php } ?>
    </form>
</div>

<script>
    $().ready(function () {
        calc_total();

        $('a.show_picture').tooltip({
            animated: 'fade',
            placement: 'top',
            html: true
        });

        $('#shipout_retailer_id').change(function () {
            var shipout_retailer_id = parseInt($(this).val()) || 0;
            if (shipout_retailer_id > 0) {
                window.location = '<?=$purchase_url ?>' + shipout_retailer_id;
            } else {
                window.location = '<?=$purchase_url ?>';
            }
        });

        $('#shipin_retailer_id').change(function () {
            var shipout_retailer_id = parseInt($('#shipout_retailer_id').val()) || 0;
            var shipin_retailer_id = parseInt($(this).val()) || 0;
            if (shipout_retailer_id > 0 && shipin_retailer_id > 0) {
                window.location = '<?=$purchase_url ?>' + shipout_retailer_id + '/' + shipin_retailer_id;
            } else {
                window.location = '<?=$purchase_url ?>' + shipout_retailer_id;
            }
        });

        $('#invoice_retailer_id').change(function () {
            var invoice_retailer_id = parseInt($(this).val()) || 0;
            if (invoice_retailer_id > 0) {
                $('#invoice_retailer').val($(this).find('option:selected').text()).addClass('d-none');
            } else {
                $('#invoice_retailer').val('').removeClass('d-none');
            }
            calc_total();
        });

        $('#invoice_send_retailer_id').change(function () {
            var invoice_send_retailer_id = parseInt($(this).val()) || 0;
            if (invoice_send_retailer_id > 0) {
                $('#invoice_send_retailer').val($(this).find('option:selected').text()).addClass('d-none');

                $('#invoice_send_address').val($(this).find('option:selected').data('address'));
            } else {
                $('#invoice_send_retailer').val('').removeClass('d-none');
                $('#invoice_send_address').val('');
            }
        });

        $('#isInvoice').change(function(){
            if ($(this).prop("checked")){
                $('#invoice_container').removeClass('d-none');
            } else {
                $('#invoice_container').addClass('d-none');
            }
        });

        $('#fare').change(function(e){
            if (!confirm('是否確定更改運費？')){
                $('#fare').val(0);
            }
        });

        $('#purchaseForm input.itemQty').change(function () {
            calc_total();
        });

        function calc_total() {
            var totalShipinStock = 0;
            var totalQty = 0;
            var subtotal = 0;
            var shipout_hasStock = $('#shipout_hasStock').val();
            var shipin_hasStock = $('#shipin_hasStock').val();

            $('#purchaseForm input.itemQty').each(function () {
                var item = $(this).parents('tr');
                var qty = parseInt($(this).val()) || 0;
                var price = parseInt($(this).data('price'));
                var shipin_stock = parseInt($(this).data('shipin-stock'));

                if (qty > 0) {
                    item.find('.item_subtotal').text('$' + numberWithCommas(price * qty));
                    totalQty += qty;
                    subtotal += price * qty;
                    if (shipin_hasStock){
                        item.find('.item_stock').text(shipin_stock + qty);
                        totalShipinStock += shipin_stock;
                    }
                } else {
                    item.find('.item_subtotal').text('');
                    if (shipin_hasStock) {
                        item.find('.item_stock').text('');
                    }
                }
            });

            $('#total_qty_text').text(numberWithCommas(totalQty));
            $('#totalQty').val(totalQty);
            $('#total_subtotal_text').text('$' + numberWithCommas(subtotal));
            $('#subtotal').val(subtotal);
            if (shipin_hasStock) {
                $('#total_stock_text').text(numberWithCommas((totalQty + totalShipinStock)));
            }

            calc_discount();
        }

        function calc_discount() {
            var total = 0;

            var discount = parseInt($('#discount').val()) || 100;

            if (($('input[type="checkbox"][name="isInvoice"]').length && $('input[type="checkbox"][name="isInvoice"]').prop('checked') == true) || $('input[type="hidden"][name="isInvoice"]').length) {
                var retailer_id = parseInt($('#retailer_id').val());
                var shipin_retailer_id = parseInt($('#shipin_retailer_id').val());
                if (retailer_id == shipin_retailer_id) {
                    var invoice_retailer_discount = $('#invoice_retailer_id').find('option:selected').data('discount');
                    if (invoice_retailer_discount != undefined && invoice_retailer_discount > 0) {
                        discount = parseInt(invoice_retailer_discount);
                    }
                }
            }

            if (discount > 100){
                discount = 100;
            }

            $('#purchaseForm input.itemQty').each(function () {
                var item = $(this).parents('tr');
                var qty = parseInt($(this).val()) || 0;
                var price = parseInt($(this).data('price'));
                var item_discount = $(this).data('discount') ? parseInt($(this).data('discount')) : discount;

                var discount_text = item_discount + '%';
                item.find('td.item_discount').text(discount_text);

                if (qty > 0) {
                    var discount_price = Math.floor(price * item_discount / 100) * qty;
                    item.find('td.item_total').text('$' + numberWithCommas(discount_price));
                    total += discount_price;
                } else {
                    item.find('td.item_total').text('');
                }
            });

            $('#total_text').text('$' + numberWithCommas(total));
        }
    });

    function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    $("#purchaseForm").keydown(function(e){
        if(e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    });

    $("#purchaseForm").submit(function (e) {
        var subtotal = parseInt($('#subtotal').val()) || 0;
        var totalQty = parseInt($('#totalQty').val()) || 0;
        if (totalQty == 0) {
            alert('請至少進貨一樣商品！');
            return false;
        }

        var match_boxamount = true;
        $('#purchaseForm input.itemQty').each(function () {
            var qty = parseInt($(this).val());
            var boxamount = parseInt($(this).data('boxamount'));
            if (qty > 0 && qty % boxamount !== 0){
                match_boxamount = false;
                return false;
            }
        });

        var is_confirm = false;
        if (!match_boxamount){
            if (confirm('此單非全部都是整箱的倍數的數量，取貨方式限定親自至輔銷單位取貨')){
                is_confirm = true;
            } else {
                return false;
            }
        } else {
            is_confirm = true;
        }

        if (is_confirm) {
            $.each($('input.itemQty'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });
        }
    });
</script><file_sep>/application/controllers/Capital_retailer_role.php
<?php

class Capital_retailer_role extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_role_model');

        $this->session->set_userdata('return_page', base_url('/capital_retailer_role/overview'));
    }

    public function overview()
    {
        $roles = $this->retailer_role_model
            ->with_level_types()
            ->order_by('id', 'asc')
            ->get_all();

        $data = [
            'roles' => $roles,
            'title' => '單位類型總覽',
            'view' => 'capital/retailer/role/overview',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/views/capital/product/relationship/edit.php
<div class="container">
    <h1 class="mb-4">編輯<?= $relationship['relation']['company'] ?>至<?= $relationship['retailer']['company'] ?>的產品折扣</h1>

    <form method="post">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th>項次</th>
                <th>貨品編號</th>
                <th>貨品名稱</th>
                <th>單價</th>
                <th>折扣 (預設<?=$relationship['discount']?>%)</th>
            </tr>
            <?php
            if ($products) {
                $i = 1;
                foreach ($products as $product_id => $product) {
                    ?>
                    <tr>
                        <td class="text-center"><?= $i ?></td>
                        <td><?= $product['p_num'] ?></td>
                        <td>
                            <?= $product['pdName'] ?> <?= $product['intro2'] ?>
                        </td>
                        <td class="item_cash text-right">$<?= number_format($product['pdCash']) ?></td>
                        <td>
                            <input type="number" name="items[<?= $product_id ?>][discount]"
                                   min="1" max="100" class="form-control text-right"
                                   value="<?= set_value('items[' . $product_id . '][discount]', isset($product_relationships[$product_id]) ? $product_relationships[$product_id]['discount'] : '') ?>"
                            />
                        </td>
                    </tr>
                    <?php
                    $i++;
                }
            }
            ?>
        </table>

        <div class="form-group d-flex justify-content-between">
            <a href="<?=base_url('/capital_relationship_shipout/overview/' . $relationship['retailer_id'])?>" class="btn btn-secondary">取消</a>
            <input type="submit" class="btn btn-success" value="更新"/>
        </div>
    </form>

</div><file_sep>/application/controllers/Capital_product_permission.php
<?php

class Capital_product_permission extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_model');
        $this->load->model('product_model');
        $this->load->model('product_permission_model');

        $this->session->set_userdata('return_page', base_url('/capital_product_permission/overview'));
    }

    public function edit($product_id)
    {
        $product = $this->product_model
            ->get($product_id);

        if (!$product_id || !$product) {
            show_error('查無商品資料');
        }

        $permission = $this->product_permission_model
            ->where('product_id', $product_id)
            ->get();

        if (!$permission){
            $permission_id = $this->product_permission_model->insert([
                'product_id' => $product_id,
            ]);

            $permission = [
                'id' => $permission_id,
                'product_id' => $product_id,
                'retailers' => [],
                'remark' => '',
            ];
        } else {
            $permission['retailers'] = explode(',', $permission['include_retailers']);
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('remark', '備註', 'max_length[200]');

            if ($this->form_validation->run() !== FALSE) {
                $include_retailers = (array)$this->input->post('include_retailers');

                $this->product_permission_model->update([
                    'include_retailers' => $include_retailers ? implode(',', $include_retailers) : null,
                    'remark' => $this->input->post('remark'),
                ], ['id' => $permission['id']]);

                redirect(base_url('/capital_product/overview/'));
            }
        }

        $retailer_selects = $this->retailer_model->getRetailerSelect();

        $data = [
            'permission' => $permission,
            'retailers' => $retailer_selects,
            'product' => $product,
            'title' => '編輯進貨商品',
            'view' => 'capital/product/permission/edit',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/views/capital/product/add.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">新增商品</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>貨品編號</label>
                    <input name="p_num" class="form-control" value="<?= set_value('p_num') ?>" required />
                </div>

                <div class="form-group">
                    <label>名稱</label>
                    <input name="pdName" class="form-control" value="<?= set_value('pdName') ?>" required />
                </div>

                <div class="form-group">
                    <label>外緣尺寸</label>
                    <input name="intro2" class="form-control" value="<?= set_value('intro2') ?>" required />
                </div>

                <div class="form-group">
                    <label>商品分類</label>
                    <?php
                    echo form_dropdown('pKind', $kind_selects, set_value('pKind'), 'class="form-control" required');
                    ?>
                </div>

                <div class="form-group">
                    <label>單價</label>
                    <input type="number" name="pdCash" class="form-control" value="<?= set_value('pdCash') ?>" required min="0" />
                </div>

                <div class="form-group">
                    <label>每箱數量</label>
                    <input type="number" name="boxAmount" class="form-control" value="<?= set_value('boxAmount') ?>" required min="1" />
                </div>

                <div class="form-group">
                    <label>有效期限</label>
                    <?php
                    echo form_dropdown('pao_id', ['' => ''] + $pao_selects, set_value('pao_id'), 'class="form-control" required');
                    ?>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/capital_product/overview/')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="新增"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/capital/level/edit.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">更新經銷規則</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>
                <div class="form-group">
                    <label>類別</label>
                    <input name="type" class="form-control-plaintext" value="<?= $level['type']['title'] ?>"/>
                </div>
                <div class="form-group">
                    <label>代碼</label>
                    <input name="code" class="form-control" value="<?= $level['code'] ?>" required />
                </div>
                <div class="form-group">
                    <label>名稱</label>
                    <input name="title" class="form-control-plaintext" value="<?= $level['type']['title'] ?>"/>
                </div>
                <div class="form-group">
                    <label>折扣</label>
                    <div class="input-group">
                        <input type="number" name="discount" class="form-control text-right" required max="100" min="1" value="<?= set_value('discount', $level['discount']) ?>"/>
                        <div class="input-group-append">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>首次進貨門檻</label>
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text">$</span>
                        </div>
                        <input type="number" name="firstThreshold" class="form-control text-right" value="<?= set_value('firstThreshold', $level['firstThreshold']) ?>"/>
                    </div>
                </div>
                <div class="form-group">
                    <label>每月進貨門檻</label>
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text">$</span>
                        </div>
                        <input type="number" name="monthThreshold" class="form-control text-right" value="<?= set_value('monthThreshold', $level['monthThreshold']) ?>"/>
                    </div>
                </div>
                <div class="form-group">
                    <label>保證金</label>
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text">$</span>
                        </div>
                        <input type="number" name="guarantee" class="form-control text-right" min="0" required value="<?= set_value('guarantee', $level['guarantee']) ?>"/>
                    </div>
                </div>

                <div class="form-group">
                    <label>補充說明</label>
                    <textarea id="remark" name="remark" class="form-control"><?= set_value('remark', $level['remark']) ?></textarea>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/capital_level/overview/')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="更新"/>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="//cdn.ckeditor.com/4.9.1/standard/ckeditor.js"></script>
<script>
    CKEDITOR.replace( 'remark', {
        allowedContent : true,
        extraAllowedContent : 'div(*)'
    });
</script><file_sep>/application/views/customer/conv_old.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">舊有會員轉換</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>電話</label>
                    <input name="phone" class="form-control" required value="<?= set_value('phone', $customer['phone']) ?>"/>
                </div>
                <div class="form-group">
                    <label>姓名</label>
                    <input name="name" class="form-control" required value="<?= set_value('name', $customer['name']) ?>"/>
                </div>
                <div class="form-group">
                    <label>性別</label>
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="gender_1"
                                   value="1"<?= set_value('gender', $customer['gender']) == '1' ? ' checked' : '' ?> required>
                            <label class="form-check-label" for="gender_1">男</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="gender_0"
                                   value="0"<?= set_value('gender', $customer['gender']) === '0' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="gender_0">女</label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="font-weight-bold">生日</label>
                    <div class="form-row">
                        <div class="col">
                            <select class="form-control" name="birthday_year">
                                <option value="">生日年</option>
                                <?php for ($i = date('Y'); $i > date('Y', strtotime('-100 years')); $i--){ ?>
                                    <option value="<?=$i?>"<?php if (set_value('birthday_year') == $i){ echo ' selected'; } ?>><?=$i?></option>
                                <?php } ?>
                            </select>
                        </div>
                        <div class="col">
                            <input id="birthday" name="birthday" required class="form-control" value="<?= set_value('birthday') ?>"/>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" value="<?= set_value('email', $customer['email']) ?>"/>
                </div>
                <div class="form-group">
                    <label>地址</label>
                    <input name="address" class="form-control" required value="<?= set_value('address', $customer['address']) ?>"/>
                </div>
                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/customer/old')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="轉換"/>
                </div>
            </form>
        </div>
    </div>
</div>

<link rel="stylesheet" href="<?= base_url('/css/datepicker.min.css')?>" />
<script src="<?= base_url('/js/datepicker.min.js')?>"></script>

<script>
    $( function() {
        $("#birthday").datepicker({
            format: 'mm/dd'
        });
    } );
</script>
<file_sep>/application/helpers/export_csv_helper.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

if ( ! function_exists('array_to_csv')) {
    function array_to_csv($data, $filename)
    {
        header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=\"".$filename.".csv\"");
        header("Pragma: no-cache");
        header("Expires: 0");

        $handle = fopen('php://output', 'w');

        foreach ($data as $i) {
            fputcsv($handle, $i, "\t");
        }

        fclose($handle);
    }
}

<file_sep>/application/controllers/Capital_pao.php
<?php

class Capital_pao extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('pao_model');

        $this->session->set_userdata('return_page', base_url('/capital_pao/overview'));
    }

    public function overview()
    {
        $total_paos_count = $this->pao_model
            ->count_rows();

        $paos = $this->pao_model
            ->paginate(20, $total_paos_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_pao', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('capital_pao', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('capital_pao', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'paos' => $paos,
            'pagination' => $this->pao_model->all_pages,
            'authority' => $authority,
            'title' => '商品期限參數總覽',
            'view' => 'capital/pao/overview',
        ];

        $this->_preload($data);
    }

    public function add()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('expiration_month', '有效期限', 'required|integer|greater_than_equal_to[1]');
            $this->form_validation->set_rules('pao_month', 'PAO', 'required|integer|greater_than_equal_to[0]');

            if ($this->form_validation->run() !== FALSE) {
                $this->pao_model->insert([
                    'expiration_month' => $this->input->post('expiration_month'),
                    'pao_month' => $this->input->post('pao_month'),
                ]);

                redirect(base_url('/capital_pao/overview/'));
            }
        }

        $data = [
            'title' => '新增商品期限參數',
            'view' => 'capital/pao/add',
        ];

        $this->_preload($data);
    }

    public function edit($pao_id)
    {
        $pao = $this->pao_model
            ->get($pao_id);

        if (!$pao_id || !$pao) {
            show_error('查無商品期限參數資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('expiration_month', '有效期限', 'required|integer|greater_than_equal_to[1]');
            $this->form_validation->set_rules('pao_month', 'PAO', 'required|integer|greater_than_equal_to[0]');

            if ($this->form_validation->run() !== FALSE) {
                $this->pao_model->update([
                    'expiration_month' => $this->input->post('expiration_month'),
                    'pao_month' => $this->input->post('pao_month'),
                ], ['id' => $pao_id]);

                redirect(base_url('/capital_pao/overview/'));
            }
        }

        $data = [
            'pao' => $pao,
            'title' => '編輯商品期限參數',
            'view' => 'capital/pao/edit',
        ];

        $this->_preload($data);
    }

    public function cancel($pao_id)
    {
        $pao = $this->pao_model
            ->get($pao_id);

        if (!$pao_id || !$pao) {
            show_error('查無經銷商品資料');
        }

        $this->load->model('product_model');
        $_products = $this->product_model
            ->where('pao_id', $pao_id)
            ->get_all();
        if ($_products){
            $products = [];
            foreach ($_products as $p){
                array_push($products, $p['pdName']);
            }
            show_error('商品(' . implode(', ', $products) . ')已經使用此效期，請先修改商品再刪除。');
        }

        $this->pao_model->delete($pao_id);

        redirect(base_url('/capital_pao/overview/'));
    }
}

?><file_sep>/application/controllers/Coupon.php
<?php

class Coupon extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged())) {
            redirect(base_url('/'));
        }

        $this->load->model('coupon_model');
        $this->load->model('confirm_model');
        $this->load->helper('data_format');

        $this->session->set_userdata('return_page', base_url('/coupon/overview'));
    }

    public function overview()
    {
        $end_month = date('Y-m-01', strtotime('+1 month'));
        $start_month = date('Y-m-01', strtotime($end_month . ' -24 month'));

        $_coupons = $this->coupon_model
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->where('coupon_month', '>=', $start_month)
            ->where('coupon_month', '<=', $end_month)
            ->order_by('coupon_month', 'desc')
            ->get_all();

        $coupons = [];
        for ($i = 0; $i < 24; $i++){
            $month = date('Y-m-01', strtotime($end_month . ' -' . $i .' month'));
            $coupon = [
                'coupon_month' => $month,
                'qty' => '',
                'first_couponNum' => '',
                'last_couponNum' => '',
                'receive_confirm' => null,
                'receive_confirm_text' => null,
            ];
            if ($_coupons){
                foreach ($_coupons as $key => $c){
                    if ($c['coupon_month'] == $month){
                        $confirm = $this->confirm_model
                            ->where('confirm_type', 'coupon')
                            ->where('confirm_id', $c['id'])
                            ->order_by('created_at', 'desc')
                            ->get();

                        if ($confirm){
                            $c['receive_confirm'] = $confirm['audit'];
                            $c['receive_confirm_text'] = confirmStatus($confirm['audit']);
                        }

                        $coupon = $c;
                        unset($_coupons[$key]);
                        break;
                    }
                }
            }
            $coupons[] = $coupon;
        }

        //權限設定
        $authority = array();
//        if ($this->authentic->authority('coupon', 'detail')){
//            $authority['detail'] = true;
//        }
        if ($this->authentic->authority('coupon', 'edit')){
            $authority['edit'] = true;
        }

        $data = [
            'coupons' => $coupons,
            'authority' => $authority,
            'title' => '折價券核發紀錄',
            'view' => 'coupon/overview',
        ];

        $this->_preload($data);
    }

//    public function detail($coupon_id)
//    {
//        $coupon = $this->coupon_model
//            ->with_approves(['with' => ['relation' => 'order', 'fields' => 'orderNum']])
//            ->with_order()
//            ->where('retailer_id', $this->dealer['retailer_id'])
//            ->get($coupon_id);
//
//        if (!$coupon_id || !$coupon){
//            show_error('查無折價券資料');
//        }
//
//        $data = [
//            'coupon' => $coupon,
//            'title' => '核發記錄明細',
//            'view' => 'coupon/detail',
//        ];
//
//        $this->_preload($data);
//    }

    public function edit($id)
    {
        $coupon = [];
        if ($id) {
            $tmp = explode('_', $id);
            if (!empty($tmp[0]) && $tmp[0] == 'month') {
                if (!empty($tmp[1]) && strtotime($tmp[1]) > 0){
                    $coupon_month = date('Y-m-01', strtotime($tmp[1]));
                    $coupon = $this->coupon_model
                        ->where('retailer_id', $this->dealer['retailer_id'])
                        ->where('coupon_month', '=', $coupon_month)
                        ->get();

                    if (!$coupon){
                        $coupon = [
                            'id' => '',
                            'coupon_month' => $coupon_month,
                            'qty' => 0,
                            'first_couponNum' => '',
                            'last_couponNum' => '',
                        ];
                    }
                }
            } else {
                $coupon_id = (int)$id;
                $coupon = $this->coupon_model
                    ->where('retailer_id', $this->dealer['retailer_id'])
                    ->get($coupon_id);
            }
        }

        if (!$coupon){
            show_error('查無折價券資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('qty', '優惠券張數', 'required|integer|greater_than_equal_to[0]');
            $this->form_validation->set_rules('first_couponNum', '首張優惠券序號', 'required|max_length[30]');
            $this->form_validation->set_rules('last_couponNum', '末張優惠券序號', 'required|max_length[30]');

            if ($coupon['id']){
                $this->coupon_model->update([
                    'qty' => $this->input->post('qty'),
                    'first_couponNum' => $this->input->post('first_couponNum'),
                    'last_couponNum' => $this->input->post('last_couponNum'),
                ], ['id' => $coupon['id']]);
            } else {
                $coupon['id'] = $this->coupon_model->insert([
                    'retailer_id' => $this->dealer['retailer_id'],
                    'coupon_month' => $coupon['coupon_month'],
                    'qty' => $this->input->post('qty'),
                    'first_couponNum' => $this->input->post('first_couponNum'),
                    'last_couponNum' => $this->input->post('last_couponNum'),
                ]);
            }

            $this->confirm_model->insert([
                'confirm_type' => 'coupon',
                'confirm_id' => $coupon['id'],
                'audit_retailer_id' => 2, //總經銷
                'dealer_id' => $this->dealer['id'],
            ]);

            redirect(base_url('/coupon/overview'));
        }

        $data = [
            'coupon' => $coupon,
            'title' => '貴賓優惠券序號登錄',
            'view' => 'coupon/edit',
        ];

        $this->_preload($data);
    }

    public function confirm()
    {
        $_confirm_group = $this->confirm_model
            ->fields('MAX(' . $this->confirm_model->get_table_name() . '.id) as id')
            ->where('confirm_type', 'coupon')
            ->where('audit_retailer_id', $this->dealer['retailer_id'])
            ->where('created_at', '>=', date('Y-m-d', strtotime('-180 days')))
            ->group_by('confirm_id')
            ->get_all();

        $confirms = [];
        if ($_confirm_group){
            $confirm_group = [];
            foreach ($_confirm_group as $cg){
                array_push($confirm_group, $cg['id']);
            }

            $total_confirms_count = $this->confirm_model
                ->where('id', $confirm_group)
                ->where('confirm_type', 'coupon')
                ->where('audit_retailer_id', $this->dealer['retailer_id'])
                ->where('audit IS NULL', null, null, false, false, true)
                ->count_rows();

            $confirms = $this->confirm_model
                ->with_coupon(['with' => ['relation' => 'retailer', 'fields' => 'company']])
                ->where('id', $confirm_group)
                ->where('confirm_type', 'coupon')
                ->where('audit_retailer_id', $this->dealer['retailer_id'])
                ->where('audit IS NULL', null, null, false, false, true)
                ->paginate(20, $total_confirms_count);
        }

        //權限設定
        $authority = array();
        if ($this->authentic->authority('coupon', 'approved')){
            $authority['approved'] = true;
        }

        $data = [
            'confirms' => $confirms,
            'pagination' => $this->confirm_model->all_pages,
            'authority' => $authority,
            'title' => '折價券審核',
            'view' => 'coupon/confirm',
        ];

        $this->_preload($data);
    }

    public function approved($confirm_id)
    {
        $confirm = $this->confirm_model
            ->with_coupon(['with' => ['relation' => 'retailer', 'fields' => 'company']])
            ->where('confirm_type', 'coupon')
            ->where('audit_retailer_id', $this->dealer['retailer_id'])
            ->where('audit IS NULL', null, null, false, false, true)
            ->get($confirm_id);

        if (!$confirm_id || !$confirm) {
            show_error('查無審核資料');
        }

        if ($this->input->post()) {
            $audit = 0;
            if (isset($_POST['approved'])) {
                $audit = 1;
            }

            $this->confirm_model->update([
                'audit' => $audit,
            ], ['id' => $confirm_id]);

            $this->session->set_userdata(array('msg' => '已經審核完畢'));

            redirect(base_url('/coupon/confirm'));
        }

        $data = [
            'confirm' => $confirm,
            'title' => '折價券審核',
            'view' => 'coupon/approved',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/views/consumer/old.php
<div class="container">
        <h1 class="mb-4 text-center">舊有會員轉換</h1>

        <form method="post">
            <?php if (validation_errors()) { ?>
                <div class="alert alert-danger">
                    <?= validation_errors() ?>
                </div>
            <?php } ?>
            <div class="row justify-content-md-center">
                <div class="col-md-8">
                    <div class="form-group">
                        <label class="font-weight-bold">舊有會員轉換說明</label>
                        <ul>
                            <li>舊有會員召回完成實名登記者即成為綠卡會員。</li>
                            <li>舊有會員一年消費未滿 12次或未單次購買12,000元於 實名登記完隔年降為飄雪白卡。</li>
                            <li>舊有會員達2年未消費，自動喪失會員資格。</li>
                        </ul>
                    </div>
                    <div class="form-group">
                        <label class="font-weight-bold">電話</label>
                        <input name="phone" class="form-control" required value="<?= set_value('phone') ?>"/>
                    </div>
                </div>
            </div>
            <div class="form-group text-center">
                <input type="submit" name="submit_buy" class="btn btn-success mr-2" value="查詢並購買"/>
                <input type="submit" class="btn btn-success" value="查詢轉換"/>
            </div>
        </form>
    </div>
</div><file_sep>/application/views/guest/admin_check_login.php
<div class="container">
    <h1 class="mb-4">總監登入確認</h1>

    <form method="post" id="purchaseForm">
        <div class="form-group">
            <div class="input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                </div>
                <input class="form-control" name="account" required placeholder="總監代號">
            </div>
        </div>
        <div class="form-group">
            <div class="input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text"><i class="fas fa-lock"></i></span>
                </div>
                <input type="<PASSWORD>" class="form-control" name="password" required placeholder="請輸入密碼">
            </div>
        </div>
        <div class="form-group d-flex justify-content-between">
            <input type="submit" value="登入" class="btn btn-lg btn-success"/>
        </div>
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?php echo validation_errors(); ?>
            </div>
        <?php } ?>
    </form>
</div><file_sep>/application/controllers/Migrate.php
<?php
//在Cli 目錄下指令php index.php migrate version XX
// XX為Migration版本號碼，1, 2, 3...

class Migrate extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        if (!$this->input->is_cli_request()) {
            show_error('你沒有權限使用');
        }

        $this->load->library('migration');
    }

    public function version($version)
    {
        if ($this->migration->version($version) === FALSE)
        {
            show_error($this->migration->error_string());
        } else {
            echo 'Migration 成功';
        }
    }
}
?><file_sep>/application/controllers/Capital_promote_method.php
<?php

class Capital_promote_method extends MY_Controller
{
    protected $dealer;
    protected $promote_type;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('promote_model');
        $this->load->model('promote_method_model');
        $this->load->model('promote_item_model');
        $this->load->model('promote_item_relative_model');
        $this->load->model('product_model');
        $this->load->model('combo_model');

        $this->promote_type = [
            1 => "產品折扣",
            2 => "滿額折扣",
            3 => "贈品",
        ];

        $this->session->set_userdata('return_page', base_url('/capital_promote/overview'));
    }

    public function overview($promote_id)
    {
        $promote = $this->promote_model
            ->get($promote_id);

        if (!$promote_id || !$promote) {
            show_error('查無優惠活動資料');
        }

        $total_methods_count = $this->promote_method_model
            ->where('promote_id', $promote_id)
            ->count_rows();

        $methods = $this->promote_method_model
            ->where('promote_id', $promote_id)
            ->order_by('sort')
            ->paginate(20, $total_methods_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_promote_method', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('capital_promote_method', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('capital_promote_method', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'promote_type' => $this->promote_type,
            'promote' => $promote,
            'methods' => $methods,
            'pagination' => $this->promote_method_model->all_pages,
            'authority' => $authority,
            'title' => '優惠方式列表',
            'view' => 'capital/promote/method/overview',
        ];

        $this->_preload($data);
    }

    public function add($promote_id, $promote_type_id = '')
    {
        $promote = $this->promote_model
            ->with_items()
            ->with_relatives()
            ->get($promote_id);

        if (!$promote_id || !$promote) {
            show_error('查無優惠活動資料');
        }

        if ($promote_type_id && !empty($this->promote_type[$promote_type_id])) {
            $products = $this->product_model->getCustomerProducts();

            $combos = $this->combo_model->getAllCombos();

            $options = null;
            if ($promote_type_id == 3) {
                $options['single'] = 0;
            }

            if ($this->input->post()) {
                $this->form_validation->set_rules('discount_type', '優惠方式', 'required|alpha|in_list[F,P]');
                if ($this->input->post('discount_type') == 'P') {
                    $this->form_validation->set_rules('discount', '優惠值', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
                } else {
                    $this->form_validation->set_rules('discount', '優惠值', 'required|integer|greater_than_equal_to[50]|less_than_equal_to[100000]');
                }

                if ($promote_type_id == 2) {
                    $this->form_validation->set_rules('limit', '滿額值', 'required|integer|greater_than_equal_to[1000]|less_than_equal_to[100000]');
                } elseif ($promote_type_id == 3) {
                    $this->form_validation->set_rules('single', '客戶只能擇一挑選贈品', 'integer');
                    $this->form_validation->set_rules('limit', '滿額值', 'required|integer|greater_than_equal_to[0]');
                }

                if ($this->form_validation->run() !== FALSE) {
                    $next_sort = $this->promote_method_model->getNextSortOfPromoteMethod($promote_id);

                    if ($promote_type_id == 3) {
                        $options['single'] = (int)$this->input->post('single');
                    }

                    $promote_method_id = $this->promote_method_model->insert([
                        'promote_id' => $promote_id,
                        'promote_type_id' => $promote_type_id,
                        'discount_type' => $this->input->post('discount_type'),
                        'discount' => $this->input->post('discount'),
                        'limit' => empty($this->input->post('limit')) ? null : $this->input->post('limit'),
                        'options' => $options ? serialize($options) : null,
                        'sort' => $next_sort,
                    ], ['id' => $promote_id]);

                    $items = (array)$this->input->post('items');
                    foreach ($items as $product_val) {
                        $tmp = explode('_', $product_val);
                        switch ($tmp[0]) {
                            case 'p':
                                $product_type = 'product';
                                break;
                            case 'c':
                                $product_type = 'combo';
                                break;
                        }
                        $product_id = $tmp[1];
                        $this->promote_item_model->insert([
                            'promote_method_id' => $promote_method_id,
                            'product_type' => $product_type,
                            'product_id' => $product_id,
                        ]);
                    }

                    $relatives = (array)$this->input->post('relatives');
                    foreach ($relatives as $product_val) {
                        $tmp = explode('_', $product_val);
                        switch ($tmp[0]) {
                            case 'p':
                                $product_type = 'product';
                                break;
                            case 'c':
                                $product_type = 'combo';
                                break;
                        }
                        $product_id = $tmp[1];
                        $this->promote_item_relative_model->insert([
                            'promote_method_id' => $promote_method_id,
                            'product_type' => $product_type,
                            'product_id' => $product_id,
                        ]);
                    }

                    redirect(base_url('/capital_promote_method/overview/' . $promote_id));
                }
            }

            $data = [
                'products' => $products,
                'combos' => $combos,
                'promote' => $promote,
                'promote_type' => $this->promote_type[$promote_type_id],
                'promote_method' => [],
                'options' => $options,
                'items' => [],
                'relatives' => [],
                'title' => '新增優惠方式',
                'view' => 'capital/promote/method/advance' . $promote_type_id,
            ];
        } else {
            $data = [
                'promote_type' => $this->promote_type,
                'promote' => $promote,
                'title' => '新增優惠方式',
                'view' => 'capital/promote/method/add',
            ];
        }

        $this->load->helper('form');

        $this->_preload($data);
    }

    public function edit($promote_method_id)
    {
        $promote_method = $this->promote_method_model
            ->with_promote()
            ->with_items()
            ->with_relatives()
            ->get($promote_method_id);

        if (!$promote_method_id || !$promote_method) {
            show_error('查無優惠方式資料');
        }

        $promote = $promote_method['promote'];
        $products = $this->product_model->getCustomerProducts();
        $combos = $this->combo_model->getAllCombos();
        $options = null;
        if ($promote_method['promote_type_id'] == 3) {
            if ($promote_method['options']){
                $options = unserialize($promote_method['options']);
            }
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('discount_type', '優惠方式', 'required|alpha|in_list[F,P]');
            if ($this->input->post('discount_type') == 'P') {
                $this->form_validation->set_rules('discount', '優惠值', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
            } else {
                $this->form_validation->set_rules('discount', '優惠值', 'required|integer|greater_than_equal_to[100]|less_than_equal_to[100000]');
            }

            if ($promote_method['promote_type_id'] == 2) {
                $this->form_validation->set_rules('limit', '滿額值', 'required|integer|greater_than_equal_to[1000]|less_than_equal_to[100000]');
            } elseif ($promote_method['promote_type_id'] == 3) {
                $this->form_validation->set_rules('single', '客戶只能擇一挑選贈品', 'integer');
                $this->form_validation->set_rules('limit', '滿額值', 'required|integer|greater_than_equal_to[0]');
            }

            if ($this->form_validation->run() !== FALSE) {
                if ($promote_method['promote_type_id'] == 3) {
                    $options['single'] = (int)$this->input->post('single');
                }

                $this->promote_method_model->update([
                    'discount_type' => $this->input->post('discount_type'),
                    'discount' => $this->input->post('discount'),
                    'limit' => empty($this->input->post('limit')) ? null : $this->input->post('limit'),
                    'options' => $options ? serialize($options) : null,
                ], ['id' => $promote_method_id]);

                $this->promote_item_model->where('promote_method_id', $promote_method_id)->delete();
                $this->promote_item_relative_model->where('promote_method_id', $promote_method_id)->delete();

                $items = (array)$this->input->post('items');
                if (!empty($items)) {
                    foreach ($items as $product_val) {
                        $tmp = explode('_', $product_val);
                        $product_type = '';
                        switch ($tmp[0]) {
                            case 'p':
                                $product_type = 'product';
                                break;
                            case 'c':
                                $product_type = 'combo';
                                break;
                        }
                        $product_id = $tmp[1];
                        if ($product_type && $product_id) {
                            $this->promote_item_model->insert([
                                'promote_method_id' => $promote_method_id,
                                'product_type' => $product_type,
                                'product_id' => $product_id,
                            ]);
                        }
                    }
                }

                $relatives = (array)$this->input->post('relatives');
                if (!empty($relatives)) {
                    foreach ($relatives as $product_val) {
                        $tmp = explode('_', $product_val);
                        $product_type = '';
                        switch ($tmp[0]) {
                            case 'p':
                                $product_type = 'product';
                                break;
                            case 'c':
                                $product_type = 'combo';
                                break;
                        }
                        $product_id = $tmp[1];
                        if ($product_type && $product_id) {
                            $this->promote_item_relative_model->insert([
                                'promote_method_id' => $promote_method_id,
                                'product_type' => $product_type,
                                'product_id' => $product_id,
                            ]);
                        }
                    }
                }

                redirect(base_url('/capital_promote_method/overview/' . $promote['id']));
            }
        }

        $_items = $promote_method['items'];
        $items = [];
        if ($_items) {
            foreach ($_items as $item) {
                if ($item['product_type'] == 'product') {
                    array_push($items, 'p_' . $item['product_id']);
                } elseif ($item['product_type'] == 'combo') {
                    array_push($items, 'c_' . $item['product_id']);
                }
            }
        }

        $_relatives = $promote_method['relatives'];
        $relatives = [];
        if ($_relatives) {
            foreach ($_relatives as $relative) {
                if ($relative['product_type'] == 'product') {
                    array_push($relatives, 'p_' . $relative['product_id']);
                } elseif ($relative['product_type'] == 'combo') {
                    array_push($relatives, 'c_' . $relative['product_id']);
                }
            }
        }

        $this->load->helper('form');

        $data = [
            'products' => $products,
            'combos' => $combos,
            'promote' => $promote,
            'promote_method' => $promote_method,
            'options' => $options,
            'items' => $items,
            'relatives' => $relatives,
            'title' => '編輯優惠方式',
            'view' => 'capital/promote/method/advance' . $promote_method['promote_type_id'],
        ];

        $this->_preload($data);
    }

    public function cancel($promote_method_id)
    {
        $promote_method = $this->promote_method_model
            ->get($promote_method_id);

        if (!$promote_method_id || !$promote_method) {
            show_error('查無優惠方式資料');
        }

        $promote_id = $promote_method['promote_id'];

        $this->promote_method_model->delete($promote_method_id);

        redirect(base_url('/capital_promote_method/overview/' . $promote_id));
    }
}

?><file_sep>/application/models/Retailer_level_type_model.php
<?php

class Retailer_level_type_model extends MY_Model
{
    public $table = 'olive_retailer_level_types';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['levels'] = array('Retailer_level_model', 'retailer_level_type_id', 'id');
    }

    public function getTypeSelect()
    {
        $_types = $this->get_all();
        $types = [];
        foreach ($_types as $type){
            $types[$type['id']] = $type['title'];
        }
        return $types;
    }
}

?>
<file_sep>/application/migrations/012_add_purchase.php
<?php
//經銷商訂貨單
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_purchase extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'retailer_address' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
            ],
            'shipin_retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'shipin_address' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
            ],
            'shipout_retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'invoice_retailer' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
            ],
            'invoice_send_retailer' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => TRUE,
            ],
            'invoice_send_address' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
            ],
            'serialNum' => [
                'type' => 'VARCHAR',
                'constraint' => 5,
            ],
            'purchaseNum' => [
                'type' => 'VARCHAR',
                'constraint' => 11,
            ],
            'totalQty' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'subtotal' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'total' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'fare' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'memo' => [
                'type' => 'TEXT',
                'null' => TRUE,
            ],
            'isInvoice' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'isConfirmed' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'isPaid' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'paid_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'isShipped' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'shipped_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'isShortage' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'isDefect' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'isReturn' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'importMethod' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'dealer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_purchases');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_purchases');
    }
}<file_sep>/application/views/capital/pao/overview.php
<div class="container">
    <h1 class="mb-4">商品期限參數設定
        <?php if (!empty($authority['add'])){ ?>
            <a href="<?= base_url('/capital_pao/add') ?>" class="btn btn-success float-right"><i class="far fa-plus-square"></i> 新增商品期限參數</a>
        <?php } ?>
    </h1>

    <table class="table table-hover table-bordered">
        <tr>
            <th>有效期限</th>
            <th>PAO</th>
            <th></th>
        </tr>
        <?php
        if ($paos) {
            foreach ($paos as $pao) {
                ?>
                <tr>
                    <td><?= $pao['expiration_month'] ?>月</td>
                    <td><?= $pao['pao_month'] ?>月</td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php if (!empty($authority['edit'])){ ?>
                                <a class="btn btn-warning btn-sm" href="<?= base_url('/capital_pao/edit/' . $pao['id']) ?>">編輯</a>
                            <?php } ?>
                            <button type="button" class="btn btn-warning btn-sm dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                <span class="sr-only">Toggle Dropdown</span>
                            </button>
                            <div class="dropdown-menu">
                                <?php if (!empty($authority['cancel'])){ ?>
                                    <div class="dropdown-divider"></div>
                                    <a class="dropdown-item" href="#"
                                       data-href="<?= base_url('/capital_pao/cancel/' . $pao['id']) ?>"
                                       data-toggle="modal" data-target="#confirm-delete"><i class="fas fa-trash"></i> 刪除</a>
                                <?php } ?>
                            </div>
                        </div>

                    </td>
                </tr>
        <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="3" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div>

<div class="modal" id="confirm-delete"  tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-trash"></i> 刪除確認</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>是否確定刪除？</p>
            </div>
            <div class="modal-footer d-flex justify-content-between">
                <button type="button" class="btn" data-dismiss="modal"><i class="fas fa-ban"></i> 取消</button>
                <a href="" class="btn btn-danger btn-confirm"><i class="fas fa-trash"></i> 刪除</a>
            </div>
        </div>
    </div>
</div>

<script>
    $().ready(function(){
        $('#confirm-delete').on('show.bs.modal', function(e){
            $(this).find('.btn-confirm').attr('href', $(e.relatedTarget).data('href'));
        });
    });
</script><file_sep>/application/controllers/Payment.php
<?php

class Payment extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!$this->dealer = $this->authentic->isLogged()) {
            redirect(base_url('/auth/login'));
        }

        $this->load->model('shipment_model');
        $this->load->model('purchase_model');
        $this->load->model('payment_model');
        $this->load->library('purchase_lib');
        $this->load->helper('data_format');

        $this->session->set_userdata('return_page', base_url('/purchase/overview'));
    }

    public function overview()
    {
        $total_payments_count = $this->payment_model
            ->where('paid_retailer_id', $this->dealer['retailer_id'])
            ->where('pay_type', '!=', 'order')
            ->count_rows();

        $payments = $this->payment_model
            ->with_paid_retailer('fields:company')
            ->with_received_retailer('fields:company')
            ->with_confirm(['non_exclusive_where' => "confirm_type='payment'"])
            ->where('paid_retailer_id', $this->dealer['retailer_id'])
            ->where('pay_type', '!=', 'order')
            ->order_by('active', 'asc')
            ->order_by('id', 'desc')
            ->paginate(20, $total_payments_count);

        if ($payments){
            foreach ($payments as $key => $payment){
                $payments[$key]['payment_confirm_label'] = $this->payment_model->generatePaymentConfirmLabel($payment, true);
            }
        }

        //權限設定
        $authority = array();
        if ($this->authentic->authority('confirm', 'overview')){
            $authority['confirm'] = true;
        }
        if ($this->authentic->authority('payment', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'payments' => $payments,
            'pagination' => $this->payment_model->all_pages,
            'authority' => $authority,
            'title' => '付款紀錄列表',
            'view' => 'payment/overview',
        ];

        $this->_preload($data);
    }

    public function purchase($purchase_id)
    {
        $purchase = $this->purchase_model
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->get($purchase_id);
        if (!$purchase_id || !$purchase) {
            show_error('查無進貨單資料');
        }
        $payment = $this->payment_model
            ->where('pay_type', 'purchase')
            ->where('pay_id', $purchase_id)
            ->where('paid_retailer_id', $this->dealer['retailer_id'])
            ->where('active', 0)
            ->get();
        if ($payment){
            redirect(base_url('/payment/add/' . $payment['id']));
        } else {
            redirect(base_url('/payment/overview'));
        }
    }

    public function add($payment_id)
    {
        $payment = $this->payment_model
            ->with_paid_retailer('fields:company')
            ->with_received_retailer()
            ->where('paid_retailer_id', $this->dealer['retailer_id'])
            ->where('active', 0)
            ->where('pay_type', '!=', 'order')
            ->get($payment_id);

        if (!$payment_id || !$payment) {
            show_error('查無付款資料');
        }

        switch ($payment['pay_type']){
            case 'purchase':
                $purchase = $this->purchase_model
                    ->with_transfer_from()
                    ->get($payment['pay_id']);
                if (!$purchase['isConfirmed']) {
                    show_error('進貨單尚未確認');
                } elseif ($purchase['isPaid']){
                    show_error('進貨單已經付款');
                } elseif (!empty($purchase['transfer_from']) && (!$purchase['transfer_from']['isPaid'] || !$purchase['transfer_from']['isPayConfirmed'])){
                    show_error('原轉單進貨單尚未付款');
                }
                break;
            case 'shipment_allowance':
                $purchase = $this->purchase_model
                    ->get($payment['pay_id']);
                if (!$purchase){
                    show_error('查無進貨單資料');
                }
                break;
        }

        $error = [];
        if ($this->input->post()) {
            $this->form_validation->set_rules('type_id', '付款方式', 'required|integer|in_list[' . implode(',', array_keys(paymentType())) . ']');

            if ($this->form_validation->run() !== FALSE) {
                if ($this->input->post('type_id') == 2) { //匯款
                    if (empty($_FILES)) {
                        $error[] = '請上傳付款憑證';
                    } else {
                        $config['upload_path'] = FCPATH . 'uploads/';
                        $config['allowed_types'] = 'gif|jpg|png';
                        $config['max_size'] = 10000000; //10M
                        $config['file_ext_tolower'] = true;
                        $config['encrypt_name'] = true;
                        $this->load->library('upload', $config);

                        $receipt = null;

                        if ($_FILES['receipt'] && $_FILES['receipt']['size']) {
                            if ($this->upload->do_upload('receipt')) {
                                $upload_data = $this->upload->data();
                                $receipt = '/uploads/' . $upload_data['file_name'];
                            } else {
                                $error[] = strip_tags($this->upload->display_errors());
                            }
                        } else {
                            $error[] = '請上傳付款憑證';
                        }
                    }
                }

                if (!$error) {
                    $this->payment_model->update([
                        'type_id' => $this->input->post('type_id'),
                        'receipt' => $receipt,
                        'active' => 1,
                        'isConfirmed' => null,
                    ], ['id' => $payment_id]);

                    switch ($payment['pay_type']) {
                        case 'purchase':
                            $unpaid_count = $this->payment_model
                                ->where('pay_type', 'purchase')
                                ->where('pay_id', $payment['pay_id'])
                                ->where('active', 0)
                                ->count_rows();

                            if (!$unpaid_count) {
                                $this->purchase_model->update(['isPaid' => 1, 'paid_at' => date('Y-m-d H:i:s')], ['id' => $payment['pay_id']]);
                            }

                            redirect(base_url('/purchase/detail/' . $payment['pay_id']));
                            break;
                        case 'shipment_allowance':
                            redirect(base_url('/transfer/detail/' . $payment['pay_id']));
                            break;
                    }
                }
            }
        }

        $data = [
            'error' => $error,
            'payment' => $payment,
            'title' => '新增付款紀錄',
            'view' => 'payment/add',
        ];

        $this->_preload($data);
    }

    public function confirms()
    {
        $total_payments_count = $this->payment_model
            ->where('received_retailer_id', $this->dealer['retailer_id'])
            ->where('pay_type', '!=', 'order')
            ->count_rows();

        $payments = $this->payment_model
            ->with_paid_retailer('fields:company')
            ->with_received_retailer('fields:company')
            ->with_confirm(['non_exclusive_where' => "confirm_type='payment'"])
            ->where('received_retailer_id', $this->dealer['retailer_id'])
            ->where('active', 1)
            ->where('pay_type', '!=', 'order')
            ->order_by('isConfirmed', 'asc')
            ->order_by('id', 'desc')
            ->paginate(20, $total_payments_count);

        if ($payments){
            foreach ($payments as $key => $payment){
                $payments[$key]['payment_confirm_label'] = $this->payment_model->generatePaymentConfirmLabel($payment, true);
            }
        }

        //權限設定
        $authority = array();
        if ($this->authentic->authority('payment', 'confirm')){
            $authority['confirm'] = true;
        }

        $data = [
            'payments' => $payments,
            'pagination' => $this->payment_model->all_pages,
            'authority' => $authority,
            'title' => '待確認收款列表',
            'view' => 'payment/confirms',
        ];

        $this->_preload($data);
    }

    public function confirm($payment_id)
    {
        $payment = $this->payment_model
            ->with_paid_retailer('fields:company')
            ->with_received_retailer('fields:company')
            ->where('received_retailer_id', $this->dealer['retailer_id'])
            ->where('active', 1)
            ->where('pay_type', '!=', 'order')
            ->get($payment_id);

        if (!$payment_id || !$payment) {
            show_error('查無付款資料');
        }

        if (!is_null($payment['isConfirmed'])){
            show_error('已確認過付款資料');
        }

        if ($this->input->post()) {
            $audit = 0;
            if (isset($_POST['confirmed'])) {
                $audit = 1;
            }

            $this->load->model('confirm_model');

            $this->confirm_model->insert([
                'confirm_type' => 'payment',
                'confirm_id' => $payment_id,
                'audit_retailer_id' => $this->dealer['retailer_id'],
                'audit' => $audit,
                'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
                'dealer_id' => $this->dealer['id'],
            ]);

            $this->payment_model->update(['active' => $audit, 'isConfirmed' => $audit], ['id' => $payment_id]);

            switch ($payment['pay_type']) {
                case 'purchase':
                    if (!$audit) {
                        $this->purchase_model->update(['isPaid' => 0, 'paid_at' => null], ['id' => $payment['pay_id']]);
                    } else {
                        $this->purchase_model->update(['isPayConfirmed' => 1], ['id' => $payment['pay_id']]);
                        $this->purchase_model->checkCorrect($payment['pay_id']);
                    }
                    redirect(base_url('/transfer/detail/' . $payment['pay_id']));
                    break;
                case 'shipment_allowance':
                    if ($audit) {
                        $this->purchase_model->checkHasAllowance($payment['pay_id']);
                        $this->purchase_model->checkCorrect($payment['pay_id']);
                    }
                    redirect(base_url('/purchase/detail/' . $payment['pay_id']));
                    break;
            }
        }

        $data = [
            'payment' => $payment,
            'title' => '確認付款',
            'view' => 'payment/confirm',
        ];

        $this->_preload($data);
    }

    public function cancel($payment_id)
    {
        $payment = $this->payment_model
            ->where('pay_type', '!=', 'order')
            ->get($payment_id);

        if (!$payment_id || !$payment) {
            show_error('查無付款資料');
        }

        if (!is_null($payment['isConfirmed'])){
            show_error('付款已經確認不能取消');
        }

        switch ($payment['pay_type']) {
            case 'purchase':
                $purchase = $this->purchase_model
                    ->get($payment['pay_id']);

                if (!$purchase) {
                    show_error('查無進貨單資料');
                }

                $this->purchase_model->update(['isPaid' => 0, 'paid_at' => null],['id' => $payment['pay_id']]);
                break;
            case 'shipment_allowance':
                $purchase = $this->purchase_model
                    ->get($payment['pay_id']);

                if (!$purchase) {
                    show_error('查無進貨單資料');
                }
                break;
        }

        $this->payment_model->delete($payment_id);

        redirect(base_url('/payment/overview'));
    }
}

?><file_sep>/application/views/capital/relationship/visor/add.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">新增輔銷關係單位</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>輔銷單位</label>
                    <?php
                    echo form_dropdown('retailer_id', ['' => ''] + $retailer_selects, set_value('retailer_id'), 'class="form-control required"');
                    ?>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/capital_relationship_visor/overview/' . $retailer['id'])?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="新增"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/coupon/detail.php
<div class="container">
    <h1 class="mb-4"><?= date('Y年m月', strtotime($coupon['coupon_month'])) ?> 核發記錄明細</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">項次</th>
            <th class="text-center">折價券編號</th>
            <th class="text-center">消費編號</th>
        </tr>
        <?php
        if ($coupon['approves']) {
            $i = 1;
            foreach ($coupon['approves'] as $approve) {
        ?>
        <tr>
            <td class="text-center">#<?= $i ?></td>
            <td class="text-center"><?= $approve['couponNum'] ?></td>
            <td class="text-center"><?= $approve['order']['orderNum'] ?></td>
            <?php
                $i++;
            }
        }
        ?>
    </table>
</div><file_sep>/application/views/capital/product/permission/overview.php
<div class="container">
    <h1 class="mb-4">進貨商品管理</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th>項次</th>
            <th>貨品編號</th>
            <th>貨品名稱</th>
            <th>單價</th>
            <th>可進貨單位</th>
            <th>備註</th>
            <th></th>
        </tr>
        <?php
        if ($products) {
            $i = 1;
            foreach ($products as $product) {
                ?>
                <tr>
                    <td class="text-center"><?= $i ?></td>
                    <td><?= $product['p_num'] ?></td>
                    <td>
                        <?= $product['pdName'] ?> <?= $product['intro2'] ?>
                    </td>
                    <td class="item_cash text-right">$<?= number_format($product['pdCash']) ?></td>
                    <td><?= empty($permissions[$product['pdId']]['retailers']) ? '全部' : implode(', ', $permissions[$product['pdId']]['retailers'])?></td>
                    <td><?= empty($permissions[$product['pdId']]['remark']) ? '' : $permissions[$product['pdId']]['remark']?></td>
                    <td>
                        <div class="btn-group" role="group">
                            <?php if (!empty($authority['edit'])){ ?>
                                <a class="btn btn-warning btn-sm" href="<?= base_url('/capital_product_permission/edit/' . $product['pdId']) ?>">編輯</a>
                            <?php } ?>
                        </div>

                    </td>
                </tr>
                <?php
                $i++;
            }
        } else {
            ?>
            <tr>
                <td colspan="7" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>
</div><file_sep>/application/migrations/068_update_retailer_active.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_retailer_active extends CI_Migration
{
    public function up()
    {
        $this->dbforge->add_column('olive_retailers', [
            'disabled_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
                'after' => 'isAllowBulk',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_retailers', 'disabled_at');
    }
}<file_sep>/application/migrations/066_update_retailer_level_code.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_retailer_level_code extends CI_Migration {

    public function up()
    {
        $this->dbforge->modify_column('olive_retailer_levels', [
            'code' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->modify_column('olive_retailer_levels', [
            'code' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'null' => TRUE,
            ],
        ]);
    }
}<file_sep>/application/views/consumer/transfer_delivery.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">A店買B店取貨之確認取貨</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>
                
                <div class="form-group">
                    <label class="font-weight-bold">收貨人</label>
                    <div><?= !empty($transfer['order']['contact']['name']) ? $transfer['order']['contact']['name'] : '' ?></div>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">連絡電話</label>
                    <div><?= !empty($transfer['order']['contact']['phone']) ? $transfer['order']['contact']['phone'] : '' ?></div>
                </div>

                <h4 class="my-4 text-center">貨品內容</h4>
                <table class="table table-hover table-bordered table-responsive-sm">
                    <tr>
                        <td>貨品名稱</td>
                        <td>訂購數量</td>
                        <td>庫存到期日</td>
                        <td>庫存數量</td>
                        <td>出貨數量</td>
                    </tr>
                    <?php
                    if ($products) {
                        foreach ($products as $product_id => $product) {
                            $stock_row = count($product['stocks']);
                            ?>
                            <tr>
                                <td rowspan="<?=$stock_row?>" class="align-middle"><?= $product['name'] ?></td>
                                <td rowspan="<?=$stock_row?>" class="align-middle text-right"><?= $product['qty'] ?></td>
                                <?php if (empty($product['stocks'][0])){ ?>
                                    <td class="align-middle"></td>
                                    <td class="align-middle">無庫存</td>
                                    <td class="align-middle"></td>
                                <?php
                                } else {
                                    $qty = min($product['qty'], $product['stocks'][0]['stock']);
                                    ?>
                                    <td class="align-middle">
                                        <?= $product['stocks'][0]['expired_at'] ? $product['stocks'][0]['expired_at'] : '未標示'?>
                                    </td>
                                    <td class="align-middle text-right"><?= number_format($product['stocks'][0]['stock']) ?></td>
                                    <td class="align-middle">
                                        <input type="number" class="form-control text-right" name="items[<?=$product_id?>][<?=$product['stocks'][0]['expired_at']?>]" max="<?=$product['stocks'][0]['stock']?>" min="0" value="<?=$qty?>" />
                                    </td>
                                <?php
                                    if ($product['qty'] == $qty){
                                        $product['qty'] = 0;
                                    } else {
                                        $product['qty'] -= $product['stocks'][0]['stock'];
                                    }
                                }
                                ?>
                            </tr>
                            <?php
                            if ($stock_row > 1){
                                foreach ($product['stocks'] as $k => $stock) {
                                    if ($k > 0) {
                                        $qty = min($product['qty'], $product['stocks'][0]['stock']);
                            ?>
                            <tr>
                                <td class="align-middle"><?= $stock['expired_at'] ? $stock['expired_at'] : '未標示' ?></td>
                                <td class="align-middle text-right"><?= number_format($stock['stock']) ?></td>
                                <td class="align-middle">
                                    <input type="number" class="form-control text-right" name="items[<?=$product_id?>][<?=$stock['expired_at']?>]" max="<?=$stock['stock']?>" min="0" value="<?=$qty?>" />
                                </td>
                            </tr>
                            <?php
                                        if ($product['qty'] == $qty){
                                            $product['qty'] = 0;
                                        } else {
                                            $product['qty'] -= $product['stocks'][0]['stock'];
                                        }
                                    }
                                }
                            }
                            ?>
                            <?php
                        }
                    }
                    ?>
                </table>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/consumer/transfer')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="確認取貨"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/capital/retailer/role/overview.php
<div class="container">
    <h1 class="mb-4">單位類型列表</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">名稱</th>
            <th></th>
        </tr>
        <?php
        if ($roles) {
            foreach ($roles as $role) {
                if (!empty($role['level_types'])){
                    foreach ($role['level_types'] as $level_type){
                        ?>
                        <tr>
                            <td class="text-center"><?= $level_type['title'] ?></td>
                            <td class="text-center">
                                <div class="btn-group" role="group">
                                    <a class="btn btn-info btn-sm"
                                       href="<?= base_url('/capital_retailer_group/overview/' . $role['id'] . '_' . $level_type['id']) ?>">群組列表</a>
                                </div>

                            </td>
                        </tr>
                        <?php
                    }
                } else {
                    ?>
                    <tr>
                        <td class="text-center"><?= $role['title'] ?></td>
                        <td class="text-center">
                            <div class="btn-group" role="group">
                                <a class="btn btn-info btn-sm"
                                   href="<?= base_url('/capital_retailer_group/overview/' . $role['id']) ?>">群組列表</a>
                            </div>

                        </td>
                    </tr>
                    <?php
                }
            }
        }
        ?>
    </table>
</div><file_sep>/application/views/coupon/approved.php
<div class="container">
    <h1 class="mb-4">審核折價券</h1>

    <?php if (validation_errors()) { ?>
        <div class="alert alert-danger">
            <?= validation_errors() ?>
        </div>
    <?php } ?>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">單位名稱</th>
            <td class="text-center"><?= $confirm['coupon']['retailer']['company'] ?></td>
        </tr>
        <tr>
            <th class="text-center">年分/月份</th>
            <td class="text-center"><?= date('Y年m月', strtotime($confirm['coupon']['coupon_month'])) ?></td>
        </tr>
        <tr>
            <th class="text-center">領用張數</th>
            <td class="text-center"><?= $confirm['coupon']['receive_qty'] ?></td>
        </tr>
    </table>

    <form method="post">
        <div class="form-group text-center">
            <input type="submit" name="refused" class="btn btn-danger" value="拒絕"/>
            <input type="submit" name="approved" class="btn btn-success" value="確認"/>
        </div>
    </form>
</div><file_sep>/application/models/Country_model.php
<?php
class Country_model extends MY_Model{
    public $table = 'country';
    public $primary_key = 'cyId';

    function __construct(){
        parent::__construct();

        $this->timestamps = false;
        $this->return_as = 'array';
    }
}
?>
<file_sep>/application/views/transfer/overview.php
<div class="container">

    <h1 class="mb-4"><?= $dealer['company'] ?> 出貨單列表</h1>
    <div>
        <p>1.  訂貨通知=送出進貨單之日期=新增進貨單</p>
        <p>2.  進貨日期=出貨日期=收貨日期=新增出貨通知之日期(因為必須同時寄出商品方能新增出貨通知)</p>
    </div>

    <form id="search_form">
        <div class="card mb-4">
            <div class="card-header">搜尋</div>
            <div class="card-body">
                <div class="form-row">
                    <div class="form-group col-md-3">
                        <label for="purchaseNum">出貨單編號</label>
                        <input class="form-control" name="purchaseNum" value="<?=$search['purchaseNum']?>" />
                    </div>
                    <div class="form-group col-md-3">
                        <label for="shipin_retailer_id">進貨單位</label>
                        <select name="shipin_retailer_id" class="form-control" required>
                            <option>全部</option>
                            <?php foreach ($shipin_retailers as $retailer){ ?>
                                <option value="<?=$retailer['id']?>"<?php if ($search['shipin_retailer_id'] == $retailer['id']){ echo 'selected'; } ?>><?=$retailer['company']?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="form-group col-md-3">
                        <label for="created_start">訂貨日期起</label>
                        <input type="date" class="form-control" name="created_start" value="<?=$search['created_start']?>" />
                    </div>
                    <div class="form-group col-md-3">
                        <label for="created_end">訂貨日期訖</label>
                        <input type="date" class="form-control" name="created_end" value="<?=$search['created_end']?>" />
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-3">
                        <label for="isConfirmed">回覆進貨單位</label>
                        <select name="isConfirmed" class="form-control">
                            <option value=""<?php if ($search['isConfirmed'] === ''){ echo 'selected';}?>>全部</option>
                            <option value="-1"<?php if ($search['isConfirmed'] === '-1'){ echo 'selected';}?>>待回覆</option>
                            <option value="1"<?php if ($search['isConfirmed'] === '1'){ echo 'selected';}?>>同意</option>
                            <option value="0"<?php if ($search['isConfirmed'] === '0'){ echo 'selected';}?>>拒絕</option>
                        </select>
                    </div>
                    <div class="form-group col-md-3">
                        <label for="isDeleted">進貨單位取消進貨</label>
                        <select name="isDeleted" class="form-control">
                            <option value=""<?php if ($search['isDeleted'] === ''){ echo 'selected';}?>>全部</option>
                            <option value="1"<?php if ($search['isDeleted'] === '1'){ echo 'selected';}?>>是</option>
                            <option value="0"<?php if ($search['isDeleted'] === '0'){ echo 'selected';}?>>否</option>
                        </select>
                    </div>
                    <div class="form-group col-md-3">
                        <label for="isPaid">收款狀態</label>
                        <select name="isPaid" class="form-control">
                            <option value=""<?php if ($search['isPaid'] === ''){ echo 'selected';}?>>全部</option>
                            <option value="1"<?php if ($search['isPaid'] === '1'){ echo 'selected';}?>>是</option>
                            <option value="0"<?php if ($search['isPaid'] === '0'){ echo 'selected';}?>>否</option>
                        </select>
                    </div>
                    <div class="form-group col-md-3">
                        <label for="isShipped">出貨決定</label>
                        <select name="isShipped" class="form-control">
                            <option value=""<?php if ($search['isShipped'] === ''){ echo 'selected';}?>>全部</option>
                            <option value="1"<?php if ($search['isShipped'] === '1'){ echo 'selected';}?>>是</option>
                            <option value="0"<?php if ($search['isShipped'] === '0'){ echo 'selected';}?>>否</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-3">
                        <label for="isReceived">收貨狀態</label>
                        <select name="isReceived" class="form-control">
                            <option value=""<?php if ($search['isShipped'] === ''){ echo 'selected';}?>>全部</option>
                            <option value="isCorrect"<?php if ($search['isReceived'] === 'isCorrect'){ echo 'selected';}?>>收貨無誤</option>
                            <option value="isRevised"<?php if ($search['isReceived'] === 'isRevised'){ echo 'selected';}?>>銷貨異動</option>
                            <option value="isReturn"<?php if ($search['isReceived'] === 'isReturn'){ echo 'selected';}?>>銷貨退回</option>
                            <option value="isAllowance"<?php if ($search['isReceived'] === 'isAllowance'){ echo 'selected';}?>>銷貨折讓</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="card-footer text-center">
                <input type="submit" value="搜尋" class="btn btn-primary" />
                <a href="<?=base_url('/transfer/overview')?>" class="btn btn-light">重設</a>
            </div>
        </div>
    </form>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">出貨單編號</th>
            <th class="text-center">訂貨日期</th>
            <th class="text-center">出貨單位</th>
            <th class="text-center">進貨單位</th>
            <th class="text-center">回覆進貨單位</th>
            <th class="text-center">進貨單位取消進貨</th>
            <th class="text-center">收款狀態</th>
            <th class="text-center">出貨決定</th>
            <th class="text-center">收貨狀態</th>
            <th class="text-center">出貨日期</th>
            <th class="text-center"></th>
        </tr>
        <?php
        if ($purchases) {
            foreach ($purchases as $purchase) {
                ?>
                <tr <?php if (!is_null($purchase['deleted_at']) || $purchase['isConfirmed'] === '0'){ ?>class="table-danger"<?php } elseif (!is_null($purchase['transfer_id'])) { ?>class="table-info"<?php } ?>>
                    <td class="text-center">
                        <?= $purchase['purchaseNum'] ?>
                        <?php if (!is_null($purchase['transfer_id'])){ ?>
                            <a class="btn btn-info btn-sm" href="<?=base_url('/purchase/overview?purchaseNum=' . $purchase['transfer_to']['purchaseNum'])?>">轉單已成立</a>
                        <?php } ?>
                    </td>
                    <td class="text-center"><?= $purchase['created_at'] ?></td>
                    <td class="text-center"><?= empty($purchase['shipout_retailer']) ? '' : $purchase['shipout_retailer']['company'] ?></td>
                    <td class="text-center"><?= $purchase['retailer']['company'] ?></td>
                    <td class="text-center"><?= $purchase['confirm_label'] ?></td>
                    <td class="text-center"><?= yesno(!is_null($purchase['deleted_at'])) ?></td>
                    <td class="text-center"><?= $purchase['paid_label'] ?></td>
                    <td class="text-center"><?= $purchase['shipped_label']?></td>
                    <td class="text-center">
                        <?php
                            if ($purchase['isShipped']) {
                                if ($purchase['isRevised']) echo '<span class="badge badge-danger mr-1">銷貨異動</span>';
                                if ($purchase['isReturn']) echo '<span class="badge badge-danger mr-1">銷貨退回</span>';
                                if ($purchase['isAllowance']) echo '<span class="badge badge-danger mr-1">銷貨折讓</span>';
                                if ($purchase['isShipConfirmed'] && !$purchase['isRevised'] && !$purchase['isReturn'] && !$purchase['isAllowance']) echo '<span class="badge badge-dark">收款無誤/結案</span>';
                            }
                        ?>
                    </td>
                    <td class="text-center"><?= $purchase['shipped_at'] ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php
                            if (!empty($authority['transfer']) && empty($purchase['order_transfer']) && is_null($purchase['transfer_id']) && is_null($purchase['isConfirmed'])) {
                                if ($purchase['shipout_retailer_id'] != 1){
                                    ?>
                                    <a class="btn btn-warning btn-sm"
                                       href="<?= base_url('/transfer/transfer/' . $purchase['id']) ?>">
                                        轉單
                                    </a>
                                    <?php
                                }
                            }
                            ?>

                            <?php
                            if (!empty($authority['confirm']) && empty($purchase['order_transfer']) && is_null($purchase['isConfirmed'])) {
                                if ($purchase['shipout_retailer_id'] == $dealer['retailer_id']) {
                                    ?>
                                    <form class="confirm_tranfer" method="post" action="<?= base_url('/transfer/confirm/' . $purchase['id']) ?>">
                                        <input type="submit" name="confirmed" class="btn btn-primary btn-sm" value="確認出貨單"/>
                                    </form>
                                    <a class="btn btn-danger btn-sm" href="#"
                                       data-href="<?= base_url('/transfer/confirm/' . $purchase['id']) ?>"
                                       data-toggle="modal" data-target="#confirm-reject">拒絕出貨單</a>
                                    <?php
                                }
                            }
                            ?>

                            <?php
                            if (!empty($authority['payment_confirm']) && $purchase['isPaid'] && !$purchase['isPayConfirmed']) {
                                foreach ( array_reverse($purchase['payments']) as $payment) {
                                    if ($payment['active'] == 1 && $payment['received_retailer_id'] == $dealer['retailer_id']){
                                        if (is_null($payment['isConfirmed'])) {
                                            ?>
                                            <a class="btn btn-primary btn-sm"
                                               href="<?= base_url('/payment/confirm/' . $payment['id']) ?>">
                                                收款作業
                                            </a>
                                            <?php
                                        }
                                        break;
                                    }
                                }
                            }
                            ?>

                            <?php if (!empty($authority['shipment_add']) && empty($purchase['order_transfer']) && (empty($purchase['transfer_to']) || (!empty($purchase['transfer_to']['transfer_to']) && $purchase['transfer_to']['transfer_to']['isShipConfirmed'])) && $purchase['isConfirmed'] && $purchase['isPaid'] && !$purchase['isShipped']) { ?>
                                <a class="btn btn-warning btn-sm"
                                   href="<?= base_url('/shipment/add/' . $purchase['id']) ?>">
                                    <i class="far fa-bell"></i> 出貨通知
                                </a>
                            <?php } ?>

                            <?php if (!empty($authority['detail'])){ ?>
                            <a class="btn btn-info btn-sm"
                               href="<?= base_url('/transfer/detail/' . $purchase['id']) ?>">
                                詳細
                            </a>
                            <?php } ?>

                            <?php if (!empty($authority['detail2'])){ ?>
                                <a class="btn btn-info btn-sm"
                                   href="<?= base_url('/transfer/detail2/' . $purchase['id']) ?>">
                                    詳細
                                </a>
                            <?php } ?>

                            <?php if (!empty($authority['shipment_detail']) && $purchase['isShipped']) { ?>
                            <button type="button" class="btn btn-info btn-sm dropdown-toggle dropdown-toggle-split"
                                    data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                <span class="sr-only">Toggle Dropdown</span>
                            </button>
                            <div class="dropdown-menu">
                                <a class="dropdown-item" href="<?= base_url('/shipment/detail/' . $purchase['id']) ?>">
                                    出貨紀錄列表
                                </a>
                            </div>
                            <?php } ?>
                        </div>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="11" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div>


<div class="modal" id="confirm-reject" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">拒絕出貨單</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>是否已通知進貨單位取消訂單？</p>
            </div>
            <div class="modal-footer d-flex justify-content-between">
                <button type="button" class="btn" data-dismiss="modal">否</button>
                <form class="confirm_tranfer" method="post">
                    <input type="submit" name="rejected" class="btn btn-danger btn-sm" value="是"/>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $().ready(function () {
        $('#confirm-reject').on('show.bs.modal', function (e) {
            $(this).find('.confirm_tranfer').attr('action', $(e.relatedTarget).data('href'));
        });
    });
</script><file_sep>/application/models/Customer_level_history_model.php
<?php

class Customer_level_history_model extends MY_Model
{
    public $table = 'olive_customer_level_histories';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['customer'] = array('foreign_model' => 'Customer_model', 'foreign_table' => 'olive_customers', 'foreign_key' => 'id', 'local_key' => 'customer_id');
        $this->has_one['old_level'] = array('foreign_model' => 'Customer_level_model', 'foreign_table' => 'olive_customer_levels', 'foreign_key' => 'id', 'local_key' => 'old_customer_level_id');
        $this->has_one['new_level'] = array('foreign_model' => 'Customer_level_model', 'foreign_table' => 'olive_customer_levels', 'foreign_key' => 'id', 'local_key' => 'new_customer_level_id');
    }
}

?>
<file_sep>/application/views/capital/privilege/apps.php
<div class="container">
    <h1 class="mb-4"><?= $class_list[$classname]['alias'] ?> 動作總覽</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <thead>
        <tr>
            <th class="text-left">動作名稱</th>
            <th></th>
        </tr>
        </thead>
        <tbody>
        <?php
        if ($class_list[$classname]['method']) {
            foreach ($class_list[$classname]['method'] as $methodname => $title) {
                ?>
                <tr>
                    <td class="text-left"><?= $title ?></td>
                    <td class="text-center">
                        <div class="btn-group">
                            <?php if (!empty($authority['authority'])){ ?>
                            <a class="btn btn-info"
                               href="<?= base_url('/capital_privilege/authority/' . $classname . '/' . $methodname) ?>">設定權限</a>
                            <?php } ?>
                        </div>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="2" class="text-center">查無資料</td>
            </tr>
        <?php } ?>
        </tbody>
    </table>
</div><file_sep>/application/models/Product_model.php
<?php

class Product_model extends MY_Model
{
    public $table = 'product';
    public $primary_key = 'pdId';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->return_as = 'array';

        $this->has_one['product_kind'] = array('foreign_model'=>'Product_kind_model','foreign_table'=>'product_kind','foreign_key'=>'ctId','local_key'=>'pKind');
        $this->has_one['pao'] = array('foreign_model'=>'Pao_model','foreign_table'=>'olive_paos','foreign_key'=>'id','local_key'=>'pao_id');
        $this->has_many['stocks'] = array('Stock_model', 'product_id', 'pdId');
        $this->has_many['permissions'] = array('Product_permission_model', 'product_id', 'pdId');
    }

    public function getProducts()
    {
        $_products = $this
            ->with_product_kind('fields:ctName')
            ->with_pao()
            ->where('boxAmount', '>', 0)
            ->where('pKind', [3,6])
            ->where('pEnable', 'Y')
            ->order_by('pKind', 'asc')
            ->order_by('sort_order', 'asc')
            ->get_all();

        $products = [];
        foreach ($_products as $p) {
            $p['qty'] = '';
            $products[$p['pdId']] = $p;
        }

        return $products;
    }

    public function getPermissionProducts($retailer_id)
    {
        $_products = $this
            ->with_product_kind('fields:ctName')
            ->with_pao()
            ->with_permissions(['non_exclusive_where' => "FIND_IN_SET(" . $retailer_id . ",include_retaifflers) AND include_retailers IS NULL"])
            ->where('pKind', [3,6])
            ->where('pEnable', 'Y')
            ->order_by('pKind', 'asc')
            ->order_by('sort_order', 'asc')
            ->get_all();

        $products = [];
        foreach ($_products as $p) {
            $p['qty'] = '';
            $products[$p['pdId']] = $p;
        }

        return $products;
    }

    public function getCustomerProducts()
    {
        $_products = $this
            ->with_product_kind('fields:ctName')
            ->with_pao()
            ->where('pKind', [3,6])
            ->where('pEnable', 'Y')
            ->order_by('pKind', 'asc')
            ->order_by('sort_order', 'asc')
            ->get_all();

        $products = [];
        foreach ($_products as $p) {
            $p['qty'] = '';
            $products[$p['pdId']] = $p;
        }

        return $products;
    }

    public function getPackageProducts()
    {
        $_products = $this
            ->with_product_kind('fields:ctName')
            ->with_pao()
            ->where('pKind', 6)
            ->where('pEnable', 'Y')
            ->order_by('pKind', 'asc')
            ->order_by('sort_order', 'asc')
            ->get_all();

        $products = [];
        foreach ($_products as $p) {
            $p['qty'] = '';
            $products[$p['pdId']] = $p;
        }

        return $products;
    }

    public function getUnitProductStocks($retailer_id)
    {
        $_products = $this
            ->with_pao()
            ->where('pKind', [3,6])
            ->where('pEnable', 'Y')
            ->order_by('pKind', 'asc')
            ->order_by('sort_order', 'asc')
            ->get_all();

        $products = [];
        $this->load->model('stock_model');
        foreach ($_products as $p) {
            $stocks = $this->stock_model
                ->where('product_id', $p['pdId'])
                ->where('retailer_id', $retailer_id)
                ->where('stock', '>', 0)
                ->order_by('expired_at', 'asc')
                ->get_all();

            $p['stocks'] = $stocks;
            $p['stock'] = $this->calcStock($stocks, $p);
            $products[$p['pdId']] = $p;
        }

        return $products;
    }

    public function calcStock($stocks, $p)
    {
        $pao_month = 0;
        if (!is_null($p['pao_id'])) {
            $pao_month = $p['pao']['pao_month'];
        }

        $stock = [
            'normal' => [
                'total' => 0,
                'data' => [],
            ],
            'nearing' => [
                'total' => 0,
                'data' => [],
            ],
            'expired' => [
                'total' => 0,
                'data' => [],
            ],
            'untag' => [
                'total' => 0,
            ],
            'total' => 0,
            'active_total' => 0,
        ];

        if (!empty($stocks)){
            foreach ($stocks as $s){
                if ($s['stock'] > 0) {
                    if (is_null($s['expired_at'])) {
                        $stock['untag']['total'] += $s['stock'];
                        $stock['active_total'] += $s['stock'];
                    } else {
                        $expired_timestamp = strtotime($s['expired_at']);
                        $today = strtotime(date('Y-m-d'));

                        if ($pao_month) {
                            $pao_timestamp = strtotime("-" . $pao_month . " months", $expired_timestamp);
                        } else {
                            $pao_timestamp = $expired_timestamp;
                        }

                        if ($today <= $pao_timestamp) {
                            $stock['normal']['total'] += $s['stock'];
                            $stock['active_total'] += $s['stock'];
                            $stock['normal']['data'][] = $s;
                        } elseif ($today > $pao_timestamp && $today <= $expired_timestamp) {
                            $stock['active_total'] += $s['stock'];
                            $stock['nearing']['total'] += $s['stock'];
                            $stock['nearing']['data'][] = $s;
                        } elseif ($today > $expired_timestamp) {
                            $stock['expired']['total'] += $s['stock'];
                            $stock['expired']['data'][] = $s;
                        }
                    }
                    $stock['total'] += $s['stock'];
                }
            }
        }

        return $stock;
    }
}

?>
<file_sep>/application/models/Customer_model.php
<?php

class Customer_model extends MY_Model
{
    public $table = 'olive_customers';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['old'] = array('foreign_model' => 'Old_customer_model', 'foreign_table' => 'olive_old_customers', 'foreign_key' => 'id', 'local_key' => 'old_customer_id');
        $this->has_one['level'] = array('foreign_model' => 'Customer_level_model', 'foreign_table' => 'olive_customer_levels', 'foreign_key' => 'id', 'local_key' => 'customer_level_id');
    }
}

?>
<file_sep>/application/models/Promote_method_model.php
<?php

class Promote_method_model extends MY_Model
{
    public $table = 'olive_promote_methods';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['promote'] = array('foreign_model' => 'Promote_model', 'foreign_table' => 'olive_promotes', 'foreign_key' => 'id', 'local_key' => 'promote_id');
        $this->has_many['items'] = array('Promote_item_model', 'promote_method_id', 'id');
        $this->has_many['relatives'] = array('Promote_item_relative_model', 'promote_method_id', 'id');
    }

    public function getNextSortOfPromoteMethod($promote_id)
    {
        $method = $this
            ->where('promote_id', $promote_id)
            ->order_by('sort', 'desc')
            ->get();

        if ($method) {
            return (int)$method['sort'] + 1;
        } else {
            return 1;
        }
    }
}

?>
<file_sep>/application/views/stock_counting/detail.php
<div class="container">
    <div class="float-right">
        <p>盤點日期: <?= date('Y/m/d', strtotime($stock_counting['created_at'])) ?></p>
        <p>盤點編號: <?= $stock_counting['countingNum'] ?></p>
        <p>盤點事由: <?= $counting_reason[$stock_counting['counting_reason']] ?></p>
    </div>
    <h1 class="mb-4"><?= $dealer['company'] ?>盤盈虧報表</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">項次</th>
            <th class="text-center">貨品編號</th>
            <th class="text-center">貨品名稱</th>
            <th class="text-center">庫存</th>
            <th class="text-center">到期日</th>
            <th class="text-center">盤點量</th>
            <th class="text-center">盤點盈虧</th>
            <th class="text-center">盤差說明</th>
            <th class="text-center">附件</th>
        </tr>
        <?php
        if ($stock_counting['items']) {
            $i = 1;
            foreach ($stock_counting['items'] as $item) {
        ?>
        <tr<?= ($item['product']['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
            <td class="text-center"><?= $i ?></td>
            <td class="text-center"><?= $item['product']['p_num'] ?></td>
            <td class="text-center"><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
            <td class="text-right"><?= $item['old_stock'] ?></td>
            <td class="text-right"><?= $item['expired_at'] ?></td>
            <td class="text-right"><?= $item['stock'] ?></td>
            <td class="text-right"><?= ($item['stock'] - $item['old_stock']) ?></td>
            <td class="text-right"><?= $item['diff_reason'] ?></td>
            <td class="text-center">
                <?php if (!is_null($item['diff_file'])){ ?>
                    <a href="<?=$item['diff_file']?>" target="_blank" class="btn btn-info">附件</a>
                <?php } ?>
            </td>
        </tr>
        <?php
                $i++;
            }
        }
        ?>

    </table>

</div><file_sep>/application/controllers/Customer.php
<?php

class Customer extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!$this->dealer = $this->authentic->isLogged()) {
            redirect(base_url('/auth/login'));
        }

        $this->load->model('customer_model');
        $this->load->model('old_customer_model');
        $this->load->library('customer_lib');
        $this->load->helper('data_format');

        $this->session->set_userdata('return_page', base_url('/customer/overview'));
    }

    public function overview()
    {
        if ($this->input->post()) {
            $this->form_validation->set_rules('name', '姓名', 'max_length[20]');
            $this->form_validation->set_rules('phone', '電話', 'is_natural|max_length[20]');
            if ($this->form_validation->run() !== FALSE && (!empty($this->input->post('name')) || !empty($this->input->post('phone')))) {
                $customers = $this->customer_model
                    ->with_level()
                    ->group_start()
                    ->where('name', $this->input->post('name'), null, true)
                    ->where('phone', $this->input->post('phone'), null, true)
                    ->group_end()
                    ->get();
                if ($customers) {
                    redirect(base_url('/customer/consumer/' . $customers['id']));
                }
            }
        }

        $data = [
            'title' => '消費者搜尋',
            'view' => 'customer/overview',
        ];

        $this->_preload($data);
    }

    public function old()
    {
        $total_customers_count = $this->old_customer_model
            ->where('isActive', 0)
            ->count_rows();

        $customers = $this->old_customer_model
            ->where('isActive', 0)
            ->order_by('id', 'desc')
            ->paginate(20, $total_customers_count);



        //權限設定
        $authority = array();
        if ($this->authentic->authority('customer', 'import')){
            $authority['import'] = true;
        }
        if ($this->authentic->authority('customer', 'old_detail')){
            $authority['old'] = true;
        }

        $data = [
            'customers' => $customers,
            'pagination' => $this->old_customer_model->all_pages,
            'authority' => $authority,
            'title' => '未轉換舊有會員資訊',
            'view' => 'customer/old',
        ];

        $this->_preload($data);
    }

    public function active_old()
    {
        $total_customers_count = $this->customer_model
            ->count_rows();

        $customers = $this->customer_model
            ->with_level()
            ->order_by('id', 'desc')
            ->paginate(20, $total_customers_count);

        $levels = $this->customer_level_model
            ->with_type()
            ->get_all();

        //權限設定
        $authority = array();
        if ($this->authentic->authority('customer', 'consumer')){
            $authority['consumer'] = true;
        }
        if ($this->authentic->authority('customer', 'old_detail')){
            $authority['old'] = true;
        }
        if ($this->authentic->authority('customer', 'export')){
            $authority['export'] = true;
        }

        $data = [
            'levels' => $levels,
            'customers' => $customers,
            'pagination' => $this->customer_model->all_pages,
            'authority' => $authority,
            'title' => '會員資料區',
            'view' => 'customer/active_old',
        ];

        $this->_preload($data);
    }

    public function old_detail($old_customer_id)
    {
        $customer = $this->old_customer_model
            ->get($old_customer_id);

        if (!$old_customer_id || !$customer) {
            show_error('查無舊有會員資料');
        }

        $data = [
            'customer' => $customer,
            'title' => '舊有會員全部匯入資訊',
            'view' => 'customer/old_detail',
        ];

        $this->_preload($data);
    }

    public function consumer($customer_id)
    {
        if (!$customer_id) {
            show_error('查無消費者資料');
        }
        $this->customer_lib->setCustomerID($customer_id);
        $this->customer_lib->downgradeCheckCustomerLevel();
        $customer = $this->customer_lib->getCustomer();

        if (!$customer) {
            show_error('查無消費者資料');
        }

        $this->load->model('order_model');
        if ($this->dealer['retailer_id'] != 2){
            $this->order_model->where('shipout_retailer_id', $this->dealer['retailer_id']);
        }
        $total_orders_count = $this->order_model
            ->where('buyer_type', 'customer')
            ->where('buyer_id', $customer_id)
            ->count_rows();

        $sortby = (int)$this->input->get('sortby');
        switch ($sortby){
            case 2: //升序
                $this->order_model->order_by($this->order_model->get_table_name().'.id', 'asc');
                break;
            case 3: //降序
                $this->order_model->order_by($this->order_model->get_table_name().'.created_at', 'desc');
                break;
            case 4: //升序
                $this->order_model->order_by($this->order_model->get_table_name().'.created_at', 'asc');
                break;
            case 5: //降序
                $this->order_model->order_by($this->order_model->get_table_name().'.total', 'desc');
                break;
            case 6: //升序
                $this->order_model->order_by($this->order_model->get_table_name().'.total', 'asc');
                break;
            case 7: //降序
                $this->order_model->order_by($this->order_model->get_table_name().'.shipout_retailer_id', 'desc');
                break;
            case 8: //升序
                $this->order_model->order_by($this->order_model->get_table_name().'.shipout_retailer_id', 'asc');
                break;
            default:
                $this->order_model->order_by($this->order_model->get_table_name().'.id', 'desc');
                break;
        }
        if ($this->dealer['retailer_id'] != 2){
            $this->order_model->where('shipout_retailer_id', $this->dealer['retailer_id']);
        }
        $orders = $this->order_model
            ->with_retailer(['fields' => 'company'])
            ->where('buyer_type', 'customer')
            ->where('buyer_id', $customer_id)
            ->paginate(20, $total_orders_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('customer', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('consumer', 'add')){
            $authority['consumer_add'] = true;
        }
        if ($this->authentic->authority('consumer', 'detail')){
            $authority['consumer_detail'] = true;
        }

        $data = [
            'customer' => $customer,
            'orders' => $orders,
            'pagination' => $this->customer_model->all_pages,
            'authority' => $authority,
            'title' => '該消費者歷史消費記錄',
            'view' => 'customer/consumer',
        ];

        $this->_preload($data);
    }

    public function upgrade($customer_id)
    {
        $this->customer_lib->setCustomerID($customer_id);
        $customer = $this->customer_lib->getCustomer();
        $customer_level_id = $this->customer_lib->upgradeLevel();
        if (!$customer_level_id || $customer_level_id != 1) {
            redirect(base_url('/customer/consumer/' . $customer_id));
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
            $this->form_validation->set_rules('phone', '電話', 'required|is_natural|max_length[20]|valid_custom_phone[' . $customer_id . ']');
            $this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
            $this->form_validation->set_rules('birthday_year', '生日年', 'integer|max_length[4]|min_length[4]');
            $this->form_validation->set_rules('birthday', '生日', 'required|valid_date');
            $this->form_validation->set_rules('email', 'Email', 'max_length[100]|valid_email');
            $this->form_validation->set_rules('address', '地址', 'required|max_length[100]');

            if ($this->form_validation->run() !== FALSE) {
                $this->customer_model->update([
                    'customer_level_id' => 1,
                    'name' => $this->input->post('name'),
                    'gender' => $this->input->post('gender'),
                    'birthday_year' => $this->input->post('birthday_year') ? $this->input->post('birthday_year') : null,
                    'birthday' => $this->input->post('birthday'),
                    'email' => $this->input->post('email'),
                    'phone' => $this->input->post('phone'),
                    'address' => $this->input->post('address'),
                ], ['id' => $customer_id]);

                $this->customer_lib->saveLevelChangeHistory(1, 1);

                redirect(base_url('/customer/consumer/' . $customer_id));
            }
        }

        $levels = $this->customer_level_model
            ->with_type()
            ->get_all();

        $data = [
            'levels' => $levels,
            'customer' => $customer,
            'title' => '符合飄雪白卡資格',
            'view' => 'customer/upgrade',
        ];

        $this->_preload($data);
    }

    public function edit($customer_id)
    {
        $customer = $this->customer_model
            ->with_level()
            ->get($customer_id);

        if (!$customer_id || !$customer) {
            show_error('查無消費者資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
            $this->form_validation->set_rules('phone', '電話', 'required|is_natural|max_length[20]|valid_custom_phone[' . $customer_id . ']');
            $this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
            $this->form_validation->set_rules('birthday_year', '生日年', 'integer|max_length[4]|min_length[4]');
            $this->form_validation->set_rules('birthday', '生日', 'required|valid_date');
            $this->form_validation->set_rules('email', 'Email', 'max_length[100]|valid_email');
            $this->form_validation->set_rules('address', '地址', 'required|max_length[100]');

            if ($this->form_validation->run() !== FALSE) {
                $this->customer_model->update([
                    'name' => $this->input->post('name'),
                    'gender' => $this->input->post('gender') ? $this->input->post('gender') : null,
                    'birthday_year' => $this->input->post('birthday_year') ? $this->input->post('birthday_year') : null,
                    'birthday' => $this->input->post('birthday') ? date('Y') . '-' . $this->input->post('birthday') : null,
                    'email' => $this->input->post('email') ? $this->input->post('email') : null,
                    'phone' => $this->input->post('phone'),
                    'address' => $this->input->post('address') ? $this->input->post('address') : null,
                ], ['id' => $customer_id]);

                redirect(base_url('/customer/consumer/' . $customer_id));
            }
        }

        $data = [
            'customer' => $customer,
            'title' => '編輯消費者',
            'view' => 'customer/edit',
        ];

        $this->_preload($data);
    }

    public function conv_old($old_customer_id)
    {
        $customer = $this->old_customer_model
            ->with_customer()
            ->where('isActive', 0)
            ->get($old_customer_id);
        if (!$old_customer_id || !$customer){
            show_error('查無舊有會員資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
            $this->form_validation->set_rules('phone', '電話', 'required|is_natural|max_length[20]|valid_custom_phone[' . $customer_id . ']');
            $this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
            $this->form_validation->set_rules('birthday_year', '生日年', 'integer|max_length[4]|min_length[4]');
            $this->form_validation->set_rules('birthday', '生日', 'required|valid_date');
            $this->form_validation->set_rules('email', 'Email', 'max_length[100]|valid_email');
            $this->form_validation->set_rules('address', '地址', 'required|max_length[100]');

            if ($this->form_validation->run() !== FALSE) {
                $customer_id = $this->customer_model->insert([
                    'old_customer_id' => $old_customer_id,
                    'customer_level_id' => 2,
                    'name' => $this->input->post('name'),
                    'gender' => $this->input->post('gender') ? $this->input->post('gender') : null,
                    'birthday_year' => $this->input->post('birthday_year') ? $this->input->post('birthday_year') : null,
                    'birthday' => $this->input->post('birthday') ? date('Y') . '-' . $this->input->post('birthday') : null,
                    'email' => $this->input->post('email') ? $this->input->post('email') : null,
                    'phone' => $this->input->post('phone'),
                    'address' => $this->input->post('address') ? $this->input->post('address') : null,
                ]);

                $this->old_customer_model->update([
                    'isActive' => 1
                ], ['id' => $old_customer_id]);

                redirect(base_url('/customer/consumer/' . $customer_id));
            }
        }

        $data = [
            'customer' => $customer,
            'title' => '舊有會員轉換',
            'view' => 'customer/conv_old',
        ];

        $this->_preload($data);
    }

    public function import()
    {
        ini_set("memory_limit","2048M");
        set_time_limit(0);

        $error = '';
        if (!empty($_FILES)) {
            $config = [
                'upload_path' => FCPATH . 'uploads/',
                'allowed_types' => 'xls',
            ];

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload('oldfile')) {
                $error = $this->upload->display_errors();
            } else {
                $data = array('upload_data' => $this->upload->data());

                $this->load->library('excel');
                $obj = PHPExcel_IOFactory::load($data['upload_data']['full_path']);
                $cell = $obj->getActiveSheet()->getCellCollection();

                $arr_data = [];
                foreach ($cell as $cl){
                    $row = $obj->getActiveSheet()->getCell($cl)->getRow();
                    $data_value = $obj->getActiveSheet()->getCell($cl)->getValue();

                    if ($row != 1){
                        if (!isset($arr_data[$row])){
                            $arr_data[$row] = [];
                        }
                        $arr_data[$row][] = $data_value;
                    }
                }

                foreach ($arr_data as $r){
                    $customerNum = @$r[1];
                    $customerNum = trim($customerNum);
                    $name = @$r[2];
                    $name = trim($name);
                    $valid_at = @$r[3];
                    if (strtotime($valid_at) > 0){
                        $valid_at = date('Y-m-d', strtotime($valid_at));
                    } else {
                        $valid_at = null;
                    }
                    $expired_at = @$r[4];
                    if (strtotime($expired_at) > 0){
                        $expired_at = date('Y-m-d', strtotime($expired_at));
                    } else {
                        $expired_at = null;
                    }
                    $gender = @$r[5];
                    $gender = trim($gender);
                    if ($gender == '男性'){
                        $gender = 1;
                    } elseif ($gender == '女性'){
                        $gender = 0;
                    } else {
                        $gender = null;
                    }
                    $phone = @$r[6];
                    $phone = trim($phone);
                    $address = @$r[7];
                    $address = trim($address);
                    $email = @$r[8];
                    $email = trim($email);
                    $isVIP = @$r[13];
                    $isVIP = trim($isVIP);
                    if ($isVIP == 'VIP'){
                        $isVIP = 1;
                    } else {
                        $isVIP = 0;
                    }
                    $first_amount = @$r[15];
                    $first_amount = (int)$first_amount;
                    $accumulate_amount = @$r[17];
                    $accumulate_amount = (int)$accumulate_amount;
                    $total_amount = @$r[19];
                    $total_amount = (int)$total_amount;
                    $amount = 0;
                    if (!$total_amount){
                        $amount = $total_amount;
                    } elseif (!$accumulate_amount){
                        $amount = $accumulate_amount;
                    } elseif (!$first_amount){
                        $amount = $first_amount;
                    }
                    $buytimes = @$r[20];
                    $buytimes = (int)$buytimes;


                    if ($customerNum){
                        $total_customers_count = $this->old_customer_model
                            ->where('customerNum', $customerNum)
                            ->count_rows();

                        if (!$total_customers_count){
                            $this->old_customer_model->insert([
                                'customerNum' => $customerNum,
                                'name' => $name,
                                'valid_at' => $valid_at,
                                'expired_at' => $expired_at,
                                'gender' => $gender,
                                'phone' => $phone,
                                'address' => $address,
                                'email' => $email,
                                'isVIP' => $isVIP,
                                'amount' => $amount,
                                'buytimes' => $buytimes,
                                'isActive' => 0,
                            ]);
                        }
                    }
                }

                @unlink($data['upload_data']['full_path']);

                $this->session->set_userdata(array('msg' => '匯入成功'));

                redirect(base_url('/customer/old/'));
            }
        }

        $data = [
            'error' => $error,
            'title' => '匯入舊有會員資訊',
            'view' => 'customer/import',
        ];

        $this->_preload($data);
    }

    public function export($old = 0)
    {
        if ($old){
            $this->customer_model->where('old_customer_id IS NOT NULL', null, null, false, false, true);
        } else {
            $this->customer_model->where('old_customer_id IS NULL', null, null, false, false, true);
        }

        $customers = $this->customer_model
            ->with_level()
            ->order_by('id', 'desc')
            ->get_all();

        $data = array();
        $data[] = array(
            '會員等級',
            '姓名',
            '性別',
            '生日',
            '聯絡電話',
            'Email',
            '地址',
        );

        if ($customers) {
            foreach ($customers as $customer) {
                $data[] = array(
                    empty($customer['level']) ? '' : $customer['level']['title'],
                    $customer['name'],
                    is_null($customer['gender']) ? '' : gender($customer['gender']),
                    ($customer['birthday_year'] ? $customer['birthday_year'] .'/' : '') . ($customer['birthday'] ? date('m/d', strtotime($customer['birthday'])) : ''),
                    $customer['phone'],
                    $customer['email'],
                    $customer['address'],
                );
            }
        }

        $this->load->helper('export_csv');
        array_to_csv($data, "customer_".time());

        exit;
    }

}

?><file_sep>/application/migrations/005_add_order.php
<?php
//經銷商訂貨單
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_order extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'buyer_type' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
                'null' => TRUE,
            ],
            'buyer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'shipout_retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'serialNum' => [
                'type' => 'VARCHAR',
                'constraint' => 5,
            ],
            'orderNum' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
            ],
            'totalQty' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'subtotal' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'total' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'memo' => [
                'type' => 'TEXT',
                'null' => TRUE,
            ],
            'isConfirmed' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'isPaid' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'isShipped' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'dealer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_orders');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_orders');
    }
}<file_sep>/application/views/stock_counting/overview.php
<div class="container">
    <h1 class="mb-4"><?= $dealer['company'] ?>歷史盤點紀錄</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">盤點編號</th>
            <th class="text-center">盤點事由</th>
            <th class="text-center">承辦人</th>
            <th></th>
        </tr>
        <?php
        if ($stock_countings) {
            foreach ($stock_countings as $stock_counting) {
                ?>
                <tr>
                    <td class="text-center"><?= $stock_counting['countingNum'] ?></td>
                    <td class="text-center"><?= $counting_reason[$stock_counting['counting_reason']] ?></td>
                    <td class="text-center"><?= $stock_counting['dealer']['name'] ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php if (!empty($authority['detail'])){ ?>
                                <a class="btn btn-info btn-sm"
                                   href="<?= base_url('/stock_counting/detail/' . $stock_counting['id']) ?>">明細</a>

                                <?php if (!empty($stock_counting['description_file'])){ ?>
                                <button type="button" class="btn btn-info btn-sm dropdown-toggle dropdown-toggle-split"
                                        data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <span class="sr-only">Toggle Dropdown</span>
                                </button>
                                <div class="dropdown-menu">
                                    <a class="dropdown-item" target="_blank" href="<?= base_url($stock_counting['description_file']) ?>">已簽名之盤點表</a>
                                </div>
                                <?php } ?>
                            <?php } ?>
                        </div>

                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="4" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div><file_sep>/application/views/capital/promote/edit.php
<div class="container">
    <h1 class="mb-4">編輯優惠活動</h1>

    <form method="post">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group">
            <label class="font-weight-bold">活動名稱</label>
            <input name="title" class="form-control" value="<?= set_value('title', $promote['title']) ?>" required/>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">開始</label>
            <input type="date" name="start_at" class="form-control" value="<?= set_value('start_at', $promote['start_at']) ?>" required/>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">結束</label>
            <input type="date" name="end_at" class="form-control" value="<?= set_value('end_at', $promote['end_at']) ?>" required/>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">可享用之優惠次數</label>
            <input type="number" name="customer_limit" class="form-control text-right" value="<?= set_value('customer_limit', $promote['customer_limit']) ?>" min="1" />
        </div>

        <div class="form-group">
            <label class="font-weight-bold">適用對象</label>
            <select name="customer_type" class="form-control">
                <?php foreach ($customer_type as $customer_type_id => $customer_type_title) { ?>
                    <option value="<?= $customer_type_id ?>"<?php if (set_value('customer_type', $promote['customer_type']) == $customer_type_id) echo 'selected';?>><?= $customer_type_title ?></option>
                <?php } ?>
            </select>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">適用對象加入開始時間</label>
            <input type="date" name="customer_start_at" class="form-control" value="<?= set_value('customer_start_at', $promote['customer_start_at']) ?>"/>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">適用對象加入結束時間</label>
            <input type="date" name="customer_end_at" class="form-control" value="<?= set_value('customer_end_at', $promote['customer_end_at']) ?>"/>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">不適用之營業單位</label>
            <select id="exclude_retailers" name="exclude_retailers[]" class="form-control" multiple>
                <?php foreach ($retailers as $retailer) { ?>
                    <option value="<?= $retailer['id'] ?>" <?php if (set_value('exclude_retailers', $promote['exclude_retailers']) && in_array($retailer['id'], set_value('exclude_retailers', $promote['exclude_retailers']))){ echo 'selected';} ?>><?= $retailer['company'] ?></option>
                <?php } ?>
            </select>
        </div>

        <div class="form-group">
            <input type="checkbox" id="go_with_member" value="1" name="go_with_member"<?php if (set_value('go_with_member', $promote['go_with_member'])){ echo ' checked';} ?>>
            <label class="form-check-label" for="go_with_member">該優惠活動可與會員優惠同時使用</label>
        </div>

        <div class="form-group">
            <input type="checkbox" id="go_with_coupon" value="1" name="go_with_coupon"<?php if (set_value('go_with_coupon', $promote['go_with_coupon'])){ echo ' checked';} ?>>
            <label class="form-check-label" for="go_with_coupon">該優惠活動可與貴賓優惠券同時使用</label>
        </div>

        <div class="form-group d-flex justify-content-between">
            <a href="<?= base_url('/capital_promote/overview/') ?>" class="btn btn-secondary">取消</a>
            <input type="submit" class="btn btn-success" value="更新"/>
        </div>
    </form>

</div>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css"
      integrity="<KEY> crossorigin="anonymous"/>
<link rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.10/select2-bootstrap.min.css"
      integrity="<KEY> crossorigin="anonymous"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"
        integrity="<KEY> crossorigin="anonymous"></script>
<script>
    $().ready(function () {
        $('#exclude_retailers').select2({
            theme: "bootstrap",
            multiple: true,
            placeholder: '選擇不適用之營業單位'
        });
    });
</script><file_sep>/application/migrations/049_add_promote_v2.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_promote_v2 extends CI_Migration {

    public function up()
    {
        $this->dbforge->drop_table('olive_promotes');

        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'title' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
            ],
            'start_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'end_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'exclude_retailers' => [
                'type' => 'VARCHAR',
                'constraint' => 255,
                'null' => TRUE,
            ],
            'customer_type' => [
                'type' => 'tinyint',
                'unsigned' => TRUE,
                'constraint' => 1,
                'null' => TRUE,
            ],
            'customer_limit' => [
                'type' => 'smallint',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'customer_start_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'customer_end_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'go_with_member' => [
                'type' => 'tinyint',
                'unsigned' => TRUE,
                'constraint' => 1,
                'default' => 0,
            ],
            'go_with_coupon' => [
                'type' => 'tinyint',
                'unsigned' => TRUE,
                'constraint' => 1,
                'default' => 0,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_promotes');

        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'promote_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'promote_type_id' => [
                'type' => 'tinyint',
                'constraint' => 2,
                'unsigned' => TRUE,
            ],
            'discount_type' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => 'P',
            ],
            'discount' => [
                'type' => 'int',
                'constraint' => 10,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'limit' => [
                'type' => 'int',
                'constraint' => 10,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'sort' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'default' => 0,
            ],
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_promote_methods');

        $this->dbforge->drop_table('olive_promote_items');
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'promote_method_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'product_type' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
                'default' => 'product',
            ],
            'product_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_promote_items');

        $this->dbforge->drop_table('olive_promote_item_relatives');
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'promote_method_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'product_type' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
                'default' => 'product',
            ],
            'product_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_promote_item_relatives');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_promotes');

        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'promote_type_id' => [
                'type' => 'tinyint',
                'constraint' => 2,
                'unsigned' => TRUE,
            ],
            'title' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
            ],
            'start_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'end_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'exclude_retailers' => [
                'type' => 'VARCHAR',
                'constraint' => 255,
                'null' => TRUE,
            ],
            'discount_type' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => 'P',
            ],
            'discount' => [
                'type' => 'int',
                'constraint' => 10,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'limit' => [
                'type' => 'int',
                'constraint' => 10,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'customer_type' => [
                'type' => 'tinyint',
                'unsigned' => TRUE,
                'constraint' => 1,
                'null' => TRUE,
            ],
            'customer_limit' => [
                'type' => 'smallint',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'customer_start_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'customer_end_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_promotes');

        $this->dbforge->drop_table('olive_promote_methods');

        $this->dbforge->drop_table('olive_promote_items');
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'promote_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'product_type' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
                'default' => 'product',
            ],
            'product_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_promote_items');

        $this->dbforge->drop_table('olive_promote_item_relatives');
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'promote_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'product_type' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
                'default' => 'product',
            ],
            'product_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_promote_item_relatives');
    }
}<file_sep>/application/migrations/010_add_shipment_item.php
<?php
//經銷商訂貨單產品
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_shipment_item extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'shipment_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'product_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'price' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'qty' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'subtotal' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'discount' => [
                'type' => 'INT',
                'constraint' => 3,
                'unsigned' => TRUE,
                'default' => 100,
            ],
            'total' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_shipment_items');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_shipment_items');
    }
}<file_sep>/application/views/guest/level.php
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1 class="mb-4">點選經銷商類別</h1>
            <form id="register_form" method="post">
                <div class="form-group">
                    <p>經銷商資格限定:</p>
                    <p>所有營業單位以及任何營業單位的所屬人員(員工、股東)都不能成為經銷商</p>
                    <p>※營業單位：包含總代理、總經銷、總代理百貨櫃位、總代理門市、皮瑪斯門市、個人經銷商、店面經銷商、櫃位經銷商</p>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="gridCheck" required>
                        <label class="form-check-label" for="gridCheck">
                            已詳閱經銷商資格限定中之內容
                        </label>
                    </div>
                </div>
                <?php
                if ($retailer_level_types) {
                    foreach ($retailer_level_types as $type => $retailer_level_type) {
                        ?>
                        <div class="form-group text-center">
                            <?php if (empty($retailer_level_type['levels'])){ ?>
                            <button name="type" class="btn-type btn btn-success" value="<?=$type?>" disabled><?=$retailer_level_type['title']?>(規劃中，敬請期待)</button>
                            <?php } else { ?>
                            <button name="type" class="btn-type btn btn-success" value="<?=$type?>"><?=$retailer_level_type['title']?></button>
                            <?php } ?>
                        </div>
                        <?php
                    }
                }
                ?>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/shipment/confirm.php
<div class="container">
    <h1 class="mb-4">確認進貨單 <?= $purchase['purchaseNum'] ?> 收貨</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th>進貨單編號</th>
            <td><?= $purchase['purchaseNum'] ?></td>
            <th>訂貨日期</th>
            <td><?= $purchase['created_at'] ?></td>
        </tr>
        <tr>
            <th>出貨單位</th>
            <td><?= $purchase['shipout_retailer']['company'] ?></td>
            <th>出貨單位回覆</th>
            <td><?=$purchase['confirm_label']?></td>
        </tr>
        <tr>
            <th>出貨決定</th>
            <td><?=$purchase['shipped_label']?></td>
            <th>進貨日期</th>
            <td><?=$purchase['shipped_at']?></td>
        </tr>
        <tr>
            <th>進貨單位付款</th>
            <td><?=$purchase['paid_label']?></td>
            <th>進貨付款日期</th>
            <td><?=$purchase['paid_at']?></td>
        </tr>
        <tr>
            <th>進貨單位</th>
            <td><?= $purchase['retailer']['invoice_title'] ?></td>
            <th>進貨單位地址</th>
            <td><?= $purchase['retailer_address'] ?></td>
        </tr>
        <tr>
            <th>收貨對象</th>
            <td><?= $purchase['shipin_retailer']['invoice_title'] ?></td>
            <th>收貨地址</th>
            <td>
                <?php
                echo $purchase['shipin_address'];
                if (!$purchase['isMatchBox']){
                    echo '<div class="text-danger">取貨方式限定親自至輔銷單位取貨</div>';
                }
                ?>
            </td>
        </tr>
        <?php if ($purchase['isInvoice']){ ?>
            <tr>
                <th>發票對象</th>
                <td colspan="3"><?= $purchase['invoice_retailer'] ?></td>
            </tr>
            <tr>
                <th>發票寄送對象</th>
                <td><?= $purchase['invoice_send_retailer'] ?></td>
                <th>發票寄送地址</th>
                <td><?= $purchase['invoice_send_address'] ?></td>
            </tr>
        <?php } ?>
        <tr>
            <th>進貨方之備註</th>
            <td><?= nl2br($purchase['memo']) ?></td>
            <th>出貨方之備註</th>
            <td><?= nl2br($shipment['memo']) ?></td>
        </tr>
    </table>

    <form method="post" id="shipmentForm" enctype="multipart/form-data">

        <h4 class="my-4 text-center">進貨明細</h4>
        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th>項次</th>
                <th>貨品編號 / 貨品名稱</th>
                <th>訂購數量</th>
                <th>到期日</th>
                <th>出貨數量</th>
                <th>收貨數量</th>
                <th>備註</th>
                <th>照片</th>
            </tr>
            <?php
            if ($shipment['items']) {
                $i = 1;
                foreach ($shipment['items'] as $item) {
                    if (empty($products[$item['product_id']])){
                        continue;
                    }
                    $stock_row = count($products[$item['product_id']]);
                    ?>
                    <tr>
                        <td class="text-center" rowspan="<?=$stock_row?>"><?= $i ?></td>
                        <td rowspan="<?=$stock_row?>"><?= $item['product']['p_num'] ?> <br /><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
                        <td class="text-right" rowspan="<?=$stock_row?>"><?= number_format($item['qty']) ?></td>
                        <?php
                        foreach ($products[$item['product_id']] as $key => $stock){
                            if ($key > 0){
                                echo '</tr><tr>';
                            }
                        ?>
                        <td><?=$stock['expired_at'] ? $stock['expired_at'] : '未標示'?></td>
                        <td class="text-right"><?= $stock['qty'] ?></td>
                        <td class="text-center">
                            <input type="number" min="0" data-stock="<?=$stock['qty']?>" class="input_qty form-control text-right" name="items[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>][qty]" value="<?= $stock['qty'] ?>" style="width: 120px;" />
                        </td>
                        <td class="text-center">
                            <textarea disabled name="items[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>][memo]" class="text_qty_memo form-control" style="min-width: 120px;"></textarea>
                        </td>
                        <td>
                            <input disabled type="file" class="input_qty_file form-control-file" name="memo_pictures[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>]" style="min-width: 120px;" />
                        </td>
                        <?php } ?>
                    </tr>
                    <?php
                    $i++;
                }
            }
            ?>
        </table>

        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group text-center">
            <a href="<?=base_url('/purchase/overview/')?>" class="btn btn-secondary">取消</a>
            <input type="submit" name="confirmed" class="btn btn-success" value="送出收貨狀態"/>
        </div>
    </form>
</div>

<script>
    $().ready(function () {
        $('.input_qty').change(function(){
            var shipin_qty = parseInt($(this).val()) || 0;
            var stock_qty = parseInt($(this).data('stock')) || 0;
            if (shipin_qty != stock_qty){
                $(this).parents('tr').find('.text_qty_memo').prop('disabled', false);
                $(this).parents('tr').find('.input_qty_file').prop('disabled', false);
            } else {
                $(this).parents('tr').find('.text_qty_memo').prop('disabled', true);
                $(this).parents('tr').find('.input_qty_file').prop('disabled', true);
            }
        });

        $("#shipmentForm").submit(function (e) {
            $.each($('input.input_qty'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });

            $.each($('textarea.text_qty_memo'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });

            $.each($('input.input_qty_file'), function () {
                if ($(this).val() == '') {
                    $(this).prop('disabled', true);
                }
            });
        });
    });
</script><file_sep>/application/views/capital/privilege/authority.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">
                <?= $class_list[$classname]['alias'] . ' (' . $class_list[$classname]['method'][$methodname] ?>) 權限
            </h1>

            <form method="post">
                <table class="table table-bordered table-striped">
                    <thead>
                    <tr>
                        <th class="text-left">群組名稱</th>
                        <th class="text-center">權限設定</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    if ($groups) {
                        foreach ($groups as $group_id => $group) {
                            ?>
                            <tr>
                                <td><?= (empty($group['level_type']) ? $group['role']['title'] : $group['level_type']['title']) . ' - ' . $group['title'] ?></td>
                                <td class="text-center">
                                    <select name="rules[<?=$group_id?>]" class="form-control">
                                        <?php foreach ($permission as $k => $v) { ?>
                                            <option value="<?= $k ?>"<?php if ($k == $group['permission']) {
                                                echo 'selected';
                                            } ?>><?= $v ?></option>
                                        <?php } ?>
                                    </select>
                                </td>
                            </tr>
                            <?php
                        }
                    }
                    ?>
                    </tbody>
                </table>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?= base_url('/capital_privilege/apps/' . $classname) ?>" class="btn btn-light">取消</a>
                    <input type="submit" value="更新" class="btn btn-primary"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/core/MY_Controller.php
<?php

class MY_Controller extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    public function _preload($data = [], $layout = 'default')
    {
        //權限
        if (!in_array($this->router->fetch_class(), ['auth', 'db', 'index'])) {
            if (!$this->authentic->authority($this->router->fetch_class(), $this->router->fetch_method())){
                show_error('您沒有瀏覽此頁面的權限');
            }
        }

        $message = $this->session->userdata('msg');
        if (!empty($message)) {
            $data['msg'] = $message;
            $this->session->unset_userdata('msg');
        }

        $data['dealer'] = $this->authentic->isLogged();
        $data['title'] = (!empty($data['title']) ? $data['title'] . '-' : '') . $this->config->item('app_title');

        if ($layout == 'default'){
            $menu = [];

            if ($this->authentic->authority('purchase', 'overview')) {
                $menu[] = [
                    'title' => '進貨單',
                    'url' => base_url('/purchase/overview'),
                ];
            }

            if ($this->authentic->authority('transfer', 'overview')) {
                $menu[] = [
                    'title' => '出貨單',
                    'url' => base_url('/transfer/overview'),
                ];
            }

            $submenu = [];
            if ($this->authentic->authority('payment', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/payment/overview'),
                    'title' => '付款紀錄列表',
                ];
            }
            if ($this->authentic->authority('payment', 'confirms')) {
                $submenu[] = [
                    'url' => base_url('/payment/confirms'),
                    'title' => '待確認收款',
                ];
            }
            if ($submenu) {
                $menu[] = [
                    'title' => '付款',
                    'submenu' => $submenu,
                ];
            }

            $submenu = [];
            if ($this->authentic->authority('stock', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/stock/overview'),
                    'title' => '即時庫存',
                ];
            }
            if ($this->authentic->authority('stock_counting', 'index')) {
                $submenu[] = [
                    'url' => base_url('/stock_counting/index'),
                    'title' => '盤點作業',
                ];
            }
            if ($submenu) {
                $menu[] = [
                    'title' => '庫存',
                    'submenu' => $submenu,
                ];
            }

            if ($this->authentic->authority('supervisor', 'overview')) {
                $menu[] = [
                    'title' => '經銷商列表',
                    'url' => base_url('/supervisor/overview'),
                ];
            }

            if (!empty($data['dealer']['retailers'])) {
                $submenu = [];
                if ($this->authentic->authority('commission', 'dealers')) {
                    $submenu[] = [
                        'url' => base_url('/commission/dealers'),
                        'title' => '輔銷人',
                    ];
                }
                if ($submenu) {
                    $menu[] = [
                        'title' => '輔銷獎金',
                        'submenu' => $submenu,
                    ];
                }
            }

            if ($this->authentic->authority('customer', 'overview')) {
                $submenu = [];
                if ($this->authentic->authority('consumer', 'add')) {
                    $submenu[] = [
                        'url' => base_url('/consumer/add'),
                        'title' => '消費者訂購',
                    ];
                }
                if ($this->authentic->authority('consumer')) {
                    $submenu[] = [
                        'url' => base_url('/consumer'),
                        'title' => '消費紀錄',
                    ];
                }
                if ($this->authentic->authority('consumer', 'old')) {
                    $submenu[] = [
                        'url' => base_url('/consumer/old'),
                        'title' => '舊有會員轉換',
                    ];
                }
                if ($this->authentic->authority('customer', 'old')) {
                    $submenu[] = [
                        'url' => base_url('/customer/old'),
                        'title' => '未轉換舊有會員',
                    ];
                }
                if ($this->authentic->authority('customer', 'active_old')) {
                    $submenu[] = [
                        'url' => base_url('/customer/active_old'),
                        'title' => '會員資料區',
                    ];
                }
                if ($this->authentic->authority('consumer', 'payAtShipped')) {
                    $submenu[] = [
                        'url' => base_url('/consumer/payAtShipped'),
                        'title' => '貨到付款管理',
                    ];
                }
                if ($this->authentic->authority('consumer', 'transfer')) {
                    $submenu[] = [
                        'url' => base_url('/consumer/transfer'),
                        'title' => 'A店買B店取貨',
                    ];
                }
                if ($submenu) {
                    $menu[] = [
                        'title' => '消費者',
                        'submenu' => $submenu,
                    ];
                }
            }

            if ($this->authentic->authority('recommend', 'overview')) {
                $submenu = [];
                if ($this->authentic->authority('recommend', 'add')) {
                    $submenu[] = [
                        'url' => base_url('/recommend/add'),
                        'title' => '來賓推薦作業',
                    ];
                }
                if ($this->authentic->authority('recommend_template')) {
                    $submenu[] = [
                        'url' => base_url('/recommend_template'),
                        'title' => '推薦函之增修',
                    ];
                }
                if ($this->authentic->authority('recommend', 'overview')) {
                    $submenu[] = [
                        'url' => base_url('/recommend/overview'),
                        'title' => '行銷作業區',
                    ];
                }
                if ($this->authentic->authority('recommend', 'temp')) {
                    $submenu[] = [
                        'url' => base_url('/recommend/temp'),
                        'title' => '暫存作業區',
                    ];
                }
                if ($submenu) {
                    $menu[] = [
                        'title' => '行銷管理',
                        'submenu' => $submenu,
                    ];
                }
            }

            $submenu = [];
            if ($this->authentic->authority('income', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/income/overview/'),
                    'title' => '營業資訊',
                ];
            }
            if ($this->authentic->authority('income', 'product')) {
                $submenu[] = [
                    'url' => base_url('/income/product/'),
                    'title' => '產品業績',
                ];
            }
            if ($submenu) {
                $menu[] = [
                    'title' => '財務管理',
                    'submenu' => $submenu,
                ];
            }

            $submenu = [];
            if ($this->authentic->authority('retailer', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/retailer/overview'),
                    'title' => '人事管理',
                ];
            }
            if ($this->authentic->authority('capital_stock', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_stock/overview'),
                    'title' => '單位庫存',
                ];
            }
            if ($this->authentic->authority('capital_product', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_product/overview'),
                    'title' => '商品管理',
                ];
            }
            if ($this->authentic->authority('capital_combo', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_combo/overview'),
                    'title' => '商品組合管理',
                ];
            }
            if ($this->authentic->authority('capital_free_package', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_free_package/overview'),
                    'title' => '免費包裝管理',
                ];
            }
            if ($this->authentic->authority('capital_promote', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_promote/overview'),
                    'title' => '優惠活動管理',
                ];
            }
//            if ($this->authentic->authority('coupon', 'confirm')) {
//                $submenu[] = [
//                    'url' => base_url('/coupon/confirm'),
//                    'title' => '折價券審核',
//                ];
//            }
            if ($this->authentic->authority('capital_retailer', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_retailer/overview'),
                    'title' => '單位管理',
                ];
            }
            if ($this->authentic->authority('capital_retailer_role', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_retailer_role/overview'),
                    'title' => '單位群組管理',
                ];
            }
            if ($this->authentic->authority('capital_privilege', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_privilege/overview'),
                    'title' => '權限管理',
                ];
            }
            if ($this->authentic->authority('capital_level', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_level/overview'),
                    'title' => '經銷規則管理',
                ];
            }
            if ($this->authentic->authority('capital_level_type', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_level_type/overview'),
                    'title' => '經銷類別管理',
                ];
            }
            if ($this->authentic->authority('capital_customer_level', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_customer_level/overview'),
                    'title' => '會員資格管理',
                ];
            }
            if ($this->authentic->authority('capital_pao', 'overview')) {
                $submenu[] = [
                    'url' => base_url('/capital_pao/overview'),
                    'title' => '商品期限參數',
                ];
            }
            if ($this->authentic->authority('capital_option', 'customer')) {
                $submenu[] = [
                    'url' => base_url('/capital_option/customer'),
                    'title' => '消費者參數',
                ];
            }

            if ($submenu) {
                $menu[] = [
                    'title' => '設定',
                    'submenu' => $submenu,
                ];
            }

            $data['menu'] = $menu;


            $right_menu = [];
            $submenu = [];
            if ($this->authentic->authority('dealer', 'edit')) {
                $submenu[] = [
                    'url' => base_url('/dealer/edit'),
                    'title' => '單位資料修改',
                ];
            }
            if ($this->authentic->authority('dealer', 'profile')) {
                $submenu[] = [
                    'url' => base_url('/dealer/profile'),
                    'title' => '個人資料修改',
                ];
            }
            if ($this->authentic->authority('dealer', 'password')) {
                $submenu[] = [
                    'url' => base_url('/dealer/password'),
                    'title' => '密碼修改',
                ];
            }
            if ($submenu) {
                $right_menu[] = [
                    'title' => '<i class="fas fa-user-circle"></i>',
                    'submenu' => $submenu,
                ];
            }
            $right_menu[] = [
                'title' => '登出',
                'url' => base_url('/auth/logout'),
            ];

            $data['right_menu'] = $right_menu;
        }

        $this->load->view('layout/' . $layout, $data);
    }
}
<file_sep>/application/models/Retailer_level_model.php
<?php

class Retailer_level_model extends MY_Model
{
    public $table = 'olive_retailer_levels';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['retailers'] = array('Retailer_model', 'retailer_level_id', 'id');
        $this->has_one['type'] = array('foreign_model' => 'Retailer_level_type_model', 'foreign_table' => 'olive_retailer_level_types', 'foreign_key' => 'id', 'local_key' => 'retailer_level_type_id');
    }

    public function getLevelSelect()
    {
        $_levels = $this
            ->with_type()
            ->get_all();
        $levels = [];
        foreach ($_levels as $level){
            $levels[$level['id']] = $level['type']['title'] . ' ' . $level['code'];
        }
        return $levels;
    }
}

?>
<file_sep>/application/views/retailer/add.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">新增<?= $dealer['company'] ?>人員</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>群組</label>
                    <?php
                    echo form_dropdown('retailer_group_id', $groups, set_value('retailer_group_id'), 'class="form-control"');
                    ?>
                </div>

                <div class="form-group">
                    <label>帳號</label>
                    <input name="account" class="form-control" minlength="3" maxlength="10" required value="<?= set_value('account') ?>" style="text-transform: lowercase;" />
                </div>

                <div class="form-group">
                    <label>姓名</label>
                    <input name="name" class="form-control" maxlength="20" required value="<?= set_value('name') ?>" />
                </div>

                <div class="form-group">
                    <label>性別</label>
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="gender_1"
                                   value="1"<?= set_value('gender') == '1' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="gender_1">男</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="gender_0"
                                   value="0"<?= set_value('gender') === '0' ? ' checked' : '' ?>>
                            <label class="form-check-label" for="gender_0">女</label>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label>登入密碼</label>
                    <input type="<PASSWORD>" name="password" class="form-control" value="" required />
                </div>
                <div class="form-group">
                    <label>確認密碼</label>
                    <input type="password" name="password_confirm" class="form-control" value="" required />
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/retailer/overview')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="新增"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/dealer/password.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">密碼修改</h1>

            <form method="post">
                <?php if (validation_errors()){ ?>
                    <div class="alert alert-danger">
                        <?=validation_errors()?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>舊密碼</label>
                    <input type="password" name="password_old" class="form-control" value="" />
                </div>
                <div class="form-group">
                    <label>登入密碼</label>
                    <input type="<PASSWORD>" name="password" class="form-control" value="" />
                </div>
                <div class="form-group">
                    <label>確認密碼</label>
                    <input type="<PASSWORD>" name="password_confirm" class="form-control" value="" />
                </div>
                <div class="form-group text-center">
                    <input type="submit" class="btn btn-success" value="更新"/>
                </div>
            </form>
        </div>
    </div>
</div>
<file_sep>/application/models/Commission_model.php
<?php

class Commission_model extends MY_Model
{
    public $table = 'olive_commissions';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['retailers'] = array('Retailer_model', 'id', 'commission_id');
        $this->has_many['dealers'] = array('Dealer_model', 'id', 'commission_id');
        $this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
    }

    //計算進貨傭金
    public function record($purchase_id)
    {
        $this->load->model('purchase_model');
        $purchase = $this->purchase_model
            ->with_retailer(['with' => ['relation' => 'level']])
            ->get($purchase_id);

        if ($purchase && $purchase['isShipConfirmed']){
            //如果原本有計算傭金紀錄則刪除重算
            $this->where('purchase_id', $purchase_id)->delete();

            //計算獎金
            $this->load->model('dealer_model');
            $this->load->model('commission_model');

            $allowance_payment_total = $this->purchase_model->sumPurchaseAllowance($purchase_id);
            $total = $purchase['total'] - $allowance_payment_total;

            //輔銷人
            $sales_dealer_id = empty($purchase['retailer']['sales_dealer_id']) ? '' : $purchase['retailer']['sales_dealer_id'];
            $sales_dealer = $this->dealer_model
                ->get($sales_dealer_id);

            //輔銷人獎金
            if ($sales_dealer && !empty($purchase['retailer']['level'])) {
                $commission_rate = 0; //大於75%折扣不給獎金
                if ($purchase['retailer']['level']['discount'] < 60) {
                    $commission_rate = 2;
                } elseif ($purchase['retailer']['level']['discount'] < 75) {
                    $commission_rate = 3;
                }
                $commission = round($total * $commission_rate / 100);

                if ($commission) {
                    $this->insert([
                        'commission_type' => 'dealer',
                        'commission_id' => $sales_dealer_id,
                        'purchase_id' => $purchase_id,
                        'total' => $commission,
                    ]);
                }
            }
        }
    }
}

?>
<file_sep>/application/models/Combo_model.php
<?php

class Combo_model extends MY_Model
{
    public $table = 'olive_combos';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['items'] = array('Combo_item_model', 'combo_id', 'id');
    }

    public function getAllCombos()
    {
        $_combos = $this
            ->get_all();

        $combos = [];
        if ($_combos) {
            foreach ($_combos as $c) {
                $c['qty'] = '';
                $combos[$c['id']] = $c;
            }
        }

        return $combos;
    }
}

?>
<file_sep>/application/migrations/014_add_customer.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_customer extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'old_customer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => true,
            ],
            'customer_level_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => true,
            ],
            'name' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
            ],
            'gender' => [
                'type' => 'tinyint',
                'unsigned' => TRUE,
                'constraint' => 1,
                'null' => true,
            ],
            'birthday_year' => [
                'type' => 'smallint',
                'constraint' => 4,
                'null' => true,
            ],
            'birthday' => [
                'type' => 'date',
                'null' => true,
            ],
            'email' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true,
            ],
            'phone' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => true,
            ],
            'address' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_customers');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_customers');
    }
}<file_sep>/application/models/Dealer_history_model.php
<?php

class Dealer_history_model extends MY_Model
{
    public $table = 'dealer_history';
    public $primary_key = 'autoid';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->return_as = 'array';
    }
}

?>
<file_sep>/application/models/Product_permission_model.php
<?php

class Product_permission_model extends MY_Model
{
    public $table = 'olive_product_permissions';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['product'] = array('foreign_model'=>'Product_model','foreign_table'=>'product','foreign_key'=>'pdId','local_key'=>'product_id');
    }

    public function getPermissionProducts($retailer_id = '')
    {
        $this->load->model('product_model');
        $products = $this->product_model->getProducts();

        if ($products){
            $_permissions = $this->get_all();
            $permissions = [];
            if ($_permissions){
                foreach ($_permissions as $k => $p){
                    $retailers = is_null($p['include_retailers']) ? null : explode(',', $p['include_retailers']);
                    $p['retailers'] = $retailers;
                    $permissions[$p['product_id']] = $p;
                }
            }

            foreach ($products as $product_id => $product){
                if (isset($permissions[$product_id])) {
                    if ($permissions[$product_id]['retailers'] && (!$retailer_id || !in_array($retailer_id, $permissions[$product_id]['retailers']))) {
                        unset($products[$product_id]);
                    }
                }
            }
        }

        return $products;
    }
}

?>
<file_sep>/application/views/supervisor/overview.php
<div class="container">
    <h1 class="mb-4">經銷商列表</h1>
    <p>起算日至結算日: <?=$search['year'].'/'.$search['month'].'/1~'.$search['month'].'/'.date("t", strtotime($search['year'].'/'.$search['month'].'/1'))?></p>
    <?php if ($dealer['sales_retailer']){ ?>
    <p>輔銷單位: <?= $dealer['sales_retailer']['company'] ?></p>
    <?php } ?>

    <form id="search_form">
        <div class="card mb-4">
            <div class="card-header">搜尋</div>
            <div class="card-body">
                <div class="form-row">
                    <div class="form-group col-md-3">
                        <label for="year">年度</label>
                        <input type="number" min="2018" max="<?=date('Y')?>" class="form-control text-right" name="year" value="<?=$search['year']?>" />
                    </div>
                    <div class="form-group col-md-3">
                        <label for="month">月份</label>
                        <input type="number" min="1" max="12" class="form-control text-right" name="month" value="<?=$search['month']?>" />
                    </div>
                    <div class="form-group col-md-3">
                        <label for="created_start">經銷商類別</label>
                        <?php
                        echo form_dropdown('retailer_level_id', ['' => ''] + $retailer_level_selects, $search['retailer_level_id'], 'class="form-control"');
                        ?>
                    </div>
                    <div class="form-group col-md-3">
                        <label for="created_start">門檻</label>
                        <?php
                        echo form_dropdown('threshold_category', ['' => ''] + $threshold_categories, $search['threshold_category'], 'class="form-control"');
                        ?>
                    </div>

                    <div class="form-group col-md-3">
                        <label class="font-weight-bold">經銷商是否失效</label>
                        <?php
                        echo form_dropdown('disabled', ['0' => '否', '1' => '是'], $search['disabled'], 'class="form-control"');
                        ?>
                    </div>

                    <?php if ($sales_retailer_select){ ?>
                    <div class="form-group col-md-3">
                        <label for="sales_retailer_id">輔銷單位</label>
                        <?php
                        echo form_dropdown('sales_retailer_id', ['' => ''] + $sales_retailer_select, $search['sales_retailer_id'], 'class="form-control"');
                        ?>
                    </div>
                    <?php } ?>

                    <?php if ($sales_dealer_select){ ?>
                        <div class="form-group col-md-3">
                            <label for="sales_dealer_id">輔銷人</label>
                            <?php
                            echo form_dropdown('sales_dealer_id', ['' => ''] + $sales_dealer_select, $search['sales_dealer_id'], 'class="form-control"');
                            ?>
                        </div>
                    <?php } ?>
                </div>
            </div>
            <div class="card-footer text-center">
                <input type="submit" value="搜尋" class="btn btn-primary" />
                <a href="<?=base_url('/supervisor/overview')?>" class="btn btn-light">重設</a>
            </div>
        </div>
    </form>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th></th>
            <th class="text-center">輔銷單位</th>
            <th class="text-center">輔銷人</th>
            <th class="text-center">經銷商名稱</th>
            <th class="text-center">經銷商類別</th>
            <th class="text-center">每月進貨門檻</th>
            <th class="text-center">本月已進貨金額</th>
            <th class="text-center">未達門檻之金額</th>
            <th class="text-center">
                超過門檻之金額 (<a href="#" data-toggle="modal" data-target="#thresholdModal">說明</a>)
            </th>
            <th></th>
        </tr>
        <?php
        if ($retailers) {
            foreach ($retailers as $retailer) {
                ?>
                <tr>
                    <td class="text-center"><?php if ($retailer['first']){ echo '首次進貨'; } ?></td>
                    <td class="text-center"><?= empty($retailer['sales_retailer']) ? '' : $retailer['sales_retailer']['company'] ?></td>
                    <td class="text-center"><?= empty($retailer['sales_dealer']) ? '' : $retailer['sales_dealer']['name'] ?></td>
                    <td class="text-center">
                        <?php if (!empty($authority['info'])){ ?>
                            <a href="<?= base_url('/supervisor/info/' . $retailer['id']) ?>">
                                <?= $retailer['company'] ?>
                            </a>
                        <?php } else { ?>
                            <?= $retailer['company'] ?>
                        <?php } ?>

                        <?php if (!is_null($retailer['disabled_at'])){ ?>
                            <br /><span class="text-danger">失效月份<?= date('Y/m', strtotime($retailer['disabled_at'])) ?></span>
                        <?php } ?>
                    </td>
                    <td class="text-center"><?= $retailer['level_title'] ?></td>
                    <td class="text-center"><?= $retailer['threshold'] ?></td>
                    <td class="text-center">$<?= number_format($retailer['total']) ?></td>
                    <td class="text-center">$<?= number_format($retailer['under']) ?></td>
                    <td class="text-center">$<?= number_format($retailer['over']) ?></td>
                    <td class="text-center">
                        <div class="btn-group" role="group">
                            <?php if (!empty($authority['purchase'])){ ?>
                                <a class="btn btn-info btn-sm"
                                   href="<?= base_url('/supervisor/purchase/' . $retailer['id'] . '/' . $search['year'] . '/' . $search['month']) ?>">
                                    進貨明細
                                </a>
                            <?php } ?>
                        </div>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="10" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div>


<div class="modal fade" id="thresholdModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <p>超過「每月進貨門檻」之金額將計入下月「本月已進貨金額」中。</p>
            </div>
        </div>
    </div>
</div><file_sep>/application/views/consumer/shipping.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">貨到付款確認寄出</h1>

            <form method="post" enctype="multipart/form-data">
                <?php if ($error) { ?>
                    <div class="alert alert-danger">
                        <?= implode('<br>', $error) ?>
                    </div>
                <?php } ?>

                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>
                
                <div class="form-group">
                    <label class="font-weight-bold">收貨人</label>
                    <div><?=$order['recipient']['name']?></div>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">連絡電話</label>
                    <div><?=$order['recipient']['phone']?></div>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">收貨地址</label>
                    <div><?=$order['recipient']['address']?></div>
                </div>

                <h4 class="my-4 text-center">貨品內容</h4>
                <table class="table table-hover table-bordered table-responsive-sm">
                    <tr>
                        <td>貨品名稱</td>
                        <td>訂購數量</td>
                        <td>庫存到期日</td>
                        <td>庫存數量</td>
                        <td>出貨數量</td>
                    </tr>
                    <?php
                    if ($products) {
                        foreach ($products as $product_id => $product) {
                            $stock_row = count($product['stocks']);
                            ?>
                            <tr>
                                <td rowspan="<?=$stock_row?>" class="align-middle"><?= $product['name'] ?></td>
                                <td rowspan="<?=$stock_row?>" class="align-middle text-right"><?= number_format($product['qty']) ?></td>
                                <?php if (empty($product['stocks'])){ ?>
                                    <td class="align-middle"></td>
                                    <td class="align-middle">無庫存</td>
                                    <td class="align-middle"></td>
                                <?php
                                } else {
                                    foreach ($product['stocks'] as $k => $stock) {
                                        $qty = min($product['qty'], $product['stocks'][0]['stock']);
                                        if ($k > 0) {
                                            echo '</tr><tr>';
                                        }
                                        ?>
                                        <td class="align-middle"><?= $stock['expired_at'] ? $stock['expired_at'] : '未標示' ?></td>
                                        <td class="align-middle text-right"><?= number_format($stock['stock']) ?></td>
                                        <td class="align-middle">
                                            <input type="number" class="form-control text-right" name="items[<?=$product_id?>][<?=$stock['expired_at']?>]" max="<?=$product['qty']?>" min="0" value="<?=$qty?>" />
                                        </td>
                                        <?php
                                        if ($product['qty'] == $qty) {
                                            $product['qty'] = 0;
                                        } else {
                                            $product['qty'] -= $qty;
                                        }
                                    }
                                }
                                ?>
                            </tr>
                            <?php
                        }
                    }
                    ?>
                </table>

                <div class="form-group">
                    <label class="font-weight-bold">運費</label>
                    <input type="number" name="freight" class="form-control text-right"
                           value="<?= set_value('freight', 0) ?>" required/>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">手續費</label>
                    <input type="number" name="fare" class="form-control text-right"
                           value="<?= set_value('fare', 0) ?>" required/>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">寄出貨品之憑證</label>
                    <input type="file" class="form-control-file" name="product_verify" />
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">運費及手續費憑證</label>
                    <input type="file" class="form-control-file" name="fare_verify" />
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">出貨時之佐證</label>
                    <input type="file" class="form-control-file" name="shipment_verify" />
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">備註</label>
                    <textarea rows="5" name="memo" class="form-control"><?= set_value('memo') ?></textarea>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/consumer/payAtShipped')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="確認寄出"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/capital/pao/add.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">新增商品期限參數</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>有效期限</label>.
                    <div class="input-group">
                        <input type="number" name="expiration_month" class="form-control text-right" value="<?= set_value('expiration_month', 1) ?>" required min="1" />
                        <div class="input-group-append">
                            <span class="input-group-text">月</span>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label>PAO</label>
                    <div class="input-group">
                        <input type="number" name="pao_month" class="form-control text-right" value="<?= set_value('pao_month', 0) ?>" required min="0" />
                        <div class="input-group-append">
                            <span class="input-group-text">月</span>
                        </div>
                    </div>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/capital_pao/overview/')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="新增"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/capital/privilege/overview.php
<div class="container">
    <h1 class="mb-4">權限總覽</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <thead>
        <tr>
            <th class="text-left">頁面名稱</th>
            <th class="text-center"></th>
        </tr>
        </thead>
        <tbody>
        <?php
        if ($class_list) {
            foreach ($class_list as $classname => $item) {
                ?>
                <tr>
                    <td class="text-left"><?= $item['alias'] ?></td>
                    <td class="text-center">
                        <div class="btn-group">
                        <?php if (!empty($authority['apps'])){ ?>
                            <a class="btn btn-info"
                               href="<?= base_url('/capital_privilege/apps/' . $classname) ?>">動作總覽</a>
                        <?php } ?>
                        </div>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="2" class="text-center">查無資料</td>
            </tr>
        <?php } ?>
        </tbody>
    </table>

</div><file_sep>/application/views/capital/stock/detail.php
<div class="container">
    <h1 class="mb-4"><?= $retailer['company'] ?>  詳細 <?= $product['pdName'] ?> <?= $product['intro2'] ?> 庫存</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">正常品</th>
            <th class="text-center">即期品</th>
            <th class="text-center">過期品</th>
            <th class="text-center">未標到期日</th>
        </tr>

        <tr>
            <td class="p-0">
                <table class="table table-hover table-bordered mb-0">
                    <tr>
                        <td>數量</td>
                        <td>到期日</td>
                    </tr>
                    <?php
                    if ($product['stock']['normal']['data']) {
                        foreach ($product['stock']['normal']['data'] as $s) {
                            ?>
                            <tr>
                                <td class="text-right"><?=number_format($s['stock'])?></td>
                                <td><?=$s['expired_at']?></td>
                            </tr>
                            <?php
                        }
                    }
                    ?>
                </table>
            </td>
            <td class="p-0">
                <table class="table table-hover table-bordered mb-0">
                    <tr>
                        <td>數量</td>
                        <td>到期日</td>
                    </tr>
                    <?php
                    if ($product['stock']['nearing']['data']) {
                        foreach ($product['stock']['nearing']['data'] as $s) {
                            ?>
                            <tr>
                                <td class="text-right"><?=number_format($s['stock'])?></td>
                                <td><?=$s['expired_at']?></td>
                            </tr>
                            <?php
                        }
                    }
                    ?>
                </table>
            </td>
            <td class="p-0">
                <table class="table table-hover table-bordered mb-0 border-0">
                    <tr>
                        <td>數量</td>
                        <td>到期日</td>
                    </tr>
                    <?php
                    if ($product['stock']['expired']['data']) {
                        foreach ($product['stock']['expired']['data'] as $s) {
                            ?>
                            <tr>
                                <td class="text-right"><?=number_format($s['stock'])?></td>
                                <td><?=$s['expired_at']?></td>
                            </tr>
                            <?php
                        }
                    }
                    ?>
                </table>
            </td>
            <td class="p-0">
                <table class="table table-hover table-bordered mb-0">
                    <tr>
                        <td>數量</td>
                    </tr>
                    <tr>
                        <td class="text-right"><?=number_format($product['stock']['untag']['total'])?></td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</div><file_sep>/application/controllers/Shipment.php
<?php

class Shipment extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!$this->dealer = $this->authentic->isLogged()) {
            redirect(base_url('/auth/login'));
        }

        $this->load->model('purchase_model');
        $this->load->model('shipment_model');
        $this->load->model('shipment_item_model');
        $this->load->model('shipment_revise_model');
        $this->load->model('shipment_revise_item_model');
        $this->load->model('shipment_expiration_model');
        $this->load->helper('data_format');
        $this->load->library('stock_lib');

        $this->session->set_userdata('return_page', base_url('/shipment/overview'));
    }

    public function overview()
    {
        $total_shipments_count = $this->shipment_model
            ->where('ship_type', 'order')
            ->where('shipin_retailer_id', $this->dealer['retailer_id'])
            ->count_rows();

        $shipments = $this->shipment_model
            ->with_confirm(['non_exclusive_where' => "confirm_type='shipment'"])
            ->with_shipout_retailer()
            ->where('ship_type', 'order')
            ->where('shipin_retailer_id', $this->dealer['retailer_id'])
            ->order_by('id', 'desc')
            ->paginate(20, $total_shipments_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('confirm', 'overview')){
            $authority['confirm_overview'] = true;
        }
        if ($this->authentic->authority('shipment', 'confirm')){
            $authority['confirm'] = true;
        }
        if ($this->authentic->authority('shipment', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'shipments' => $shipments,
            'pagination' => $this->shipment_model->all_pages,
            'authority' => $authority,
            'title' => '收貨紀錄列表',
            'view' => 'shipment/overview',
        ];

        $this->_preload($data);
    }

    public function detail($purchase_id)
    {
        $purchase = $this->purchase_model
            ->with_transfer_from(['with' => [
                ['relation' => 'shipin_retailer', 'fields' => 'company,invoice_title'],
                ['relation' => 'retailer', 'fields' => 'company,invoice_title'],
            ]
            ])
            ->group_start()
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->where('shipout_retailer_id', $this->dealer['retailer_id'], null, true)
            ->group_end()
            ->get($purchase_id);

        if (!$purchase) {
            show_error('查無出貨單資料');
        }

        $ship_data = [
            'title' => '進貨單 ' . $purchase['purchaseNum'],
            'add' => (!$purchase['isShipped'] && $purchase['shipout_retailer_id'] == $this->dealer['retailer_id']) ? true : false,
            'add_url' => base_url('/shipment/add/' . $purchase_id)
        ];

        $total_shipments_count = $this->shipment_model
            ->where('ship_type', 'purchase')
            ->where('ship_id', $purchase_id)
            ->count_rows();

        $shipments = $this->shipment_model
            ->with_confirm(['non_exclusive_where' => "confirm_type='shipment'"])
            ->with_shipout_retailer()
            ->with_shipin_retailer()
            ->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
            ->where('ship_type', 'purchase')
            ->where('ship_id', $purchase_id)
            ->order_by('id', 'desc')
            ->paginate(20, $total_shipments_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('shipment', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('confirm', 'overview')){
            $authority['confirm_overview'] = true;
        }
        if ($this->authentic->authority('shipment', 'confirm')){
            $authority['confirm'] = true;
        }
        if ($this->authentic->authority('shipment', 'cancel')){
            $authority['cancel'] = true;
        }

        $data = [
            'purchase' => $purchase,
            'ship_data' => $ship_data,
            'shipments' => $shipments,
            'pagination' => $this->shipment_model->all_pages,
            'authority' => $authority,
            'title' => '出貨紀錄列表',
            'view' => 'shipment/detail',
        ];

        $this->_preload($data);
    }

    public function add($purchase_id)
    {
        $purchase = $this->purchase_model
            ->with_retailer('fields:company')
            ->with_shipin_retailer('fields:company,invoice_title')
            ->with_shipout_retailer('fields:company')
            ->with_items()
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get($purchase_id);

        if (!$purchase) {
            show_error('查無出貨單資料');
        }

        if (!$purchase['isConfirmed']) {
            show_error('此出貨單未確認');
        }

        if (!$purchase['isPaid']) {
            show_error('此出貨單未付款');
        }

        if ($purchase['isShipped']) {
            show_error('此出貨單已出貨');
        }

        $this->load->model('purchase_item_model');
        $items = $this->purchase_item_model
            ->with_product()
            ->where('purchase_id', $purchase_id)
            ->get_all();

        if (!$items){
            show_error('此出貨單無商品資料');
        } else {
            $products = [];

            foreach ($items as $item){
                if (!isset($products[$item['product_id']])){
                    $stocks = $this->stock_model
                        ->where('product_id', $item['product_id'])
                        ->where('retailer_id', $this->dealer['retailer_id'])
                        ->where('stock', '>', 0)
                        ->group_start()
                        ->where('expired_at', '>=', date('Y-m-d'), true)
                        ->where('expired_at IS NULL', null, null, true, false, true)
                        ->group_end()
                        ->order_by('ISNULL(expired_at)', 'asc')
                        ->order_by('expired_at', 'asc')
                        ->get_all();

                    $products[$item['product_id']] = [
                        'name' => $item['product']['pdName'] . $item['product']['intro2'],
                        'qty' => 0,
                        'stocks' => $stocks,
                    ];
                }
                $products[$item['product_id']]['qty'] += $item['qty'];
            }
        }

        $eta_limit = [
            'start' => date('Y-m-d', strtotime($purchase['paid_at'])),
            'end' => date('Y-m-d', strtotime($purchase['paid_at'].' + ' . $this->dealer['eta_days'] .' days')),
        ];

        if ($this->input->post()) {
            $this->form_validation->set_rules('eta_at', '出貨日期', 'required|valid_date');
            $this->form_validation->set_rules('fare', '運費', 'required|integer|greater_than_equal_to[0]');

            $check_expired_options = [
                'products' => $products,
                'items' => $this->input->post('items'),
            ];

            $this->form_validation->set_rules('items', '出貨數量', 'callback_check_shipping_qty[' . json_encode($check_expired_options) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $shipment_id = $this->shipment_model->insert([
                    'ship_type' => 'purchase',
                    'ship_id' => $purchase_id,
                    'shipout_retailer_id' => $purchase['shipout_retailer_id'],
                    'shipin_retailer_id' => $purchase['retailer_id'],
                    'eta_at' => $this->input->post('eta_at'),
                    'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
                    'retailer_id' => $this->dealer['retailer_id'],
                    'dealer_id' => $this->dealer['id'],
                ]);

                $this->purchase_model->update(['isShipped' => 1, 'shipped_at' => $this->input->post('eta_at')], ['id' => $purchase_id]);

                //轉單要再複製一個出貨單
                $transfer_purchase = $this->purchase_model
                    ->where('transfer_id', $purchase_id)
                    ->get();

                if ($transfer_purchase){
                    $transfer_shipment_id = $this->shipment_model->insert([
                        'shipment_id' => $shipment_id,
                        'ship_type' => 'purchase',
                        'ship_id' => $transfer_purchase['id'],
                        'shipout_retailer_id' => $transfer_purchase['shipout_retailer_id'],
                        'shipin_retailer_id' => $transfer_purchase['retailer_id'],
                        'eta_at' => $this->input->post('eta_at'),
                        'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
                        'retailer_id' => $this->dealer['retailer_id'],
                        'dealer_id' => $this->dealer['id'],
                    ]);

                    $this->purchase_model->update(['isShipped' => 1, 'shipped_at' => $this->input->post('eta_at')], ['id' => $transfer_purchase['id']]);
                }

                foreach ($purchase['items'] as $item) {
                    $this->shipment_item_model->insert([
                        'shipment_id' => $shipment_id,
                        'product_id' => $item['product_id'],
                        'qty' => $item['qty'],
                    ]);

                    if ($transfer_purchase){
                        $this->shipment_item_model->insert([
                            'shipment_id' => $transfer_shipment_id,
                            'product_id' => $item['product_id'],
                            'qty' => $item['qty'],
                        ]);
                    }
                }

                //紀錄產品有效期限
                $items = (array)$this->input->post('items');
                foreach ($items as $product_id => $expired_data) {
                    foreach ($expired_data as $expired_at => $qty) {
                        if ($qty > 0) {
                            $this->shipment_expiration_model->insert([
                                'shipment_id' => $shipment_id,
                                'product_id' => $product_id,
                                'expired_at' => $expired_at ? $expired_at : null,
                                'qty' => $qty,
                            ]);

                            if ($transfer_purchase){
                                $this->shipment_expiration_model->insert([
                                    'shipment_id' => $transfer_shipment_id,
                                    'product_id' => $product_id,
                                    'expired_at' => $expired_at ? $expired_at : null,
                                    'qty' => $qty,
                                ]);
                            }
                        }
                    }
                }

                //出貨扣庫
                $this->stock_lib->shipout_confirm($shipment_id);

                //運費
                $fare = $this->input->post('fare');
                if ($fare > 0) {
                    $this->load->model('expense_model');
                    $this->expense_model->insert([
                        'retailer_id' => $purchase['shipout_retailer_id'],
                        'event_type' => 'shipment',
                        'event_id' => $shipment_id,
                        'expense_type' => 'freight',
                        'price' => $fare,
                        'dealer_id' => $this->dealer['id'],
                    ]);
                }

                redirect(base_url('/transfer/detail/' . $purchase_id));
            }
        }

        $data = [
            'eta_limit' => $eta_limit,
            'purchase' => $purchase,
            'products' => $products,
            'title' => '新增出貨紀錄',
            'view' => 'shipment/add',
        ];

        $this->_preload($data);
    }

    public function check_shipping_qty($i, $params)
    {
        $params = json_decode($params, true);
        $products = (array)$params['products'];
        $items = (array)$params['items'];
        $error = '';

        if (!$items) {
            $error = '無輸入任何商品';
        } else {
            foreach ($products as $product_id => $product){
                if (!isset($items[$product_id])) {
                    $error = '輸入的商品未輸入數量';
                    break;
                }

                $shipping_qty = 0;
                $expired_data = $items[$product_id];
                foreach ($expired_data as $expired_at => $qty){
                    if ($qty > 0) {
                        $match_stock = false;
                        foreach ($product['stocks'] as $stock){
                            if ((is_null($stock['expired_at']) && empty($expired_at)) || $stock['expired_at'] == $expired_at){
                                if ($stock['stock'] < $qty){
                                    $error = '輸入的商品出貨數量大於有效日之庫存';
                                    break 3;
                                }
                                $match_stock = true;
                            }
                        }

                        if (!$match_stock) {
                            $error = '輸入的商品庫存到期日有誤';
                            break 2;
                        }
                        $shipping_qty += $qty;
                    }
                }

                if ($product['qty'] != $shipping_qty){
                    $error = '輸入的商品訂購數量與出貨總量不符';
                    break;
                }
            }
        }

        if (!$error) {
            return true;
        } else {
            $this->form_validation->set_message('check_shipping_qty', $error);
            return false;
        }
    }

    public function confirm($shipment_id)
    {
        $shipment = $this->shipment_model
            ->with_items(['with' => ['relation' => 'product']])
            ->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
            ->where('ship_type', 'purchase')
            ->where('isRevised', 0)
            ->where('isReturn', 0)
            ->where('shipin_retailer_id', $this->dealer['retailer_id'])
            ->get($shipment_id);

        if (!$shipment_id || !$shipment) {
            show_error('查無收貨資料');
        }

        if (!is_null($shipment['isConfirmed'])){
            show_error('已確認過收貨資料');
        }

        $purchase = $this->purchase_model
            ->with_transfer_from()
            ->with_retailer('fields:company,invoice_title')
            ->with_shipin_retailer('fields:company,invoice_title')
            ->with_shipout_retailer('fields:company,invoice_title')
            ->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
            ->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
            ->get($shipment['ship_id']);

        if (!$purchase) {
            show_error('查無出貨單資料');
        }

        if (!empty($purchase['transfer_from'])) {
            show_error('轉單不能收貨確認');
        }

        $transfer_shipment = [];
        if (!is_null($purchase['transfer_id'])) {
            $transfer_shipment = $this->shipment_model
                ->get($shipment['shipment_id']);
        }

        $_products = $this->shipment_expiration_model
            ->where('shipment_id', $shipment_id)
            ->get_all();

        $products = [];
        if ($_products){
            foreach ($_products as $p){
                if (!isset($products[$p['product_id']])){
                    $products[$p['product_id']] = [];
                }
                $p['expired_at'] = is_null($p['expired_at']) ? 0 : $p['expired_at'];
                $products[$p['product_id']][] = $p;
            }
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('items', '數量', 'callback_check_qty[' . json_encode(['shipment_items' => $shipment['items'], 'products' => $products, 'items' => $this->input->post('items')]) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $items = (array)$this->input->post('items');
                $memo_pictures = empty($_FILES['memo_pictures']) ? [] : $_FILES['memo_pictures'];

                $isAllCorrect = true;

                $config['upload_path'] = FCPATH . 'uploads/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = 10000000; //10M
                $config['file_ext_tolower'] = true;
                $config['encrypt_name'] = true;
                $this->load->library('upload', $config);

                foreach ($shipment['items'] as $shipment_item) {
                    $product_id = $shipment_item['product_id'];
                    foreach ($products[$product_id] as $stock) {
                        $stock_qty = $stock['qty'];
                        $shipin_qty = $items[$product_id][$stock['expired_at']]['qty'];
                        if ($stock_qty != $shipin_qty) {
                            $isAllCorrect = false;
                        }
                    }
                }

                $this->load->model('confirm_model');
                $this->confirm_model->confirmed('shipment', $shipment_id, 1, $this->dealer);
                $this->shipment_model->update(['isConfirmed' => 1], ['id' => $shipment_id]);

                if ($transfer_shipment) {
                    $this->confirm_model->confirmed('shipment', $transfer_shipment['id'], 1, $this->dealer);
                    $this->shipment_model->update(['isConfirmed' => 1], ['id' => $transfer_shipment['id']]);
                }

                if ($isAllCorrect){
                    $this->stock_lib->shipin_confirm($shipment_id);
                    $this->purchase_model->checkCorrect($shipment['ship_id']);
                    if ($transfer_shipment) {
                        $this->purchase_model->checkCorrect($transfer_shipment['ship_id']);
                    }
                } else {
                    $this->purchase_model->update(['isRevised' => 1], ['id' => $shipment['ship_id']]);

                    $shipment_revise_id = $this->shipment_revise_model->insert([
                        'shipment_id' => $shipment_id,
                        'isConfirmed' => 0,
                        'retailer_id' => $this->dealer['retailer_id'],
                        'dealer_id' => $this->dealer['id'],
                    ]);

                    if ($transfer_shipment) {
                        $this->purchase_model->update(['isRevised' => 1], ['id' => $transfer_shipment['ship_id']]);

                        $transfer_shipment_revise_id = $this->shipment_revise_model->insert([
                            'shipment_id' => $transfer_shipment['id'],
                            'isConfirmed' => 0,
                            'retailer_id' => $this->dealer['retailer_id'],
                            'dealer_id' => $this->dealer['id'],
                        ]);
                    }

                    foreach ($shipment['items'] as $shipment_item) {
                        $product_id = $shipment_item['product_id'];

                        foreach ($products[$product_id] as $stock) {
                            $memo_picture = null;
                            $shipin_qty = $items[$product_id][$stock['expired_at']]['qty'];

                            if ($memo_pictures && !empty($memo_pictures['size'][$product_id][$stock['expired_at']])) {
                                $_FILES['image']['name'] = $memo_pictures['name'][$product_id][$stock['expired_at']];
                                $_FILES['image']['type'] = $memo_pictures['type'][$product_id][$stock['expired_at']];
                                $_FILES['image']['tmp_name'] = $memo_pictures['tmp_name'][$product_id][$stock['expired_at']];
                                $_FILES['image']['error'] = $memo_pictures['error'][$product_id][$stock['expired_at']];
                                $_FILES['image']['size'] = $memo_pictures['size'][$product_id][$stock['expired_at']];

                                if ($this->upload->do_upload('image')) {
                                    $upload_data = $this->upload->data();
                                    $memo_picture = '/uploads/' . $upload_data['file_name'];
                                }
                            }

                            $memo = empty($items[$product_id][$stock['expired_at']]['memo']) ? '' : $items[$product_id][$stock['expired_at']]['memo'];

                            $this->shipment_revise_item_model->insert([
                                'shipment_revise_id' => $shipment_revise_id,
                                'product_id' => $product_id,
                                'expired_at' => $stock['expired_at'] ? $stock['expired_at'] : null,
                                'qty' => $shipin_qty,
                                'memo' => $memo,
                                'memo_file' => $memo_picture,
                            ]);

                            if ($transfer_shipment) {
                                $this->shipment_revise_item_model->insert([
                                    'shipment_revise_id' => $transfer_shipment_revise_id,
                                    'product_id' => $product_id,
                                    'expired_at' => $stock['expired_at'] ? $stock['expired_at'] : null,
                                    'qty' => $shipin_qty,
                                    'memo' => $memo,
                                    'memo_file' => $memo_picture,
                                ]);
                            }
                        }
                    }
                }

                redirect(base_url('/purchase/detail/' . $purchase['id']));
            }
        }

        $this->load->library('purchase_lib');
        $purchase_lib = new purchase_lib($purchase);
        $purchase['paid_label'] = $purchase_lib->generatePaidLabel(true);
        $purchase['confirm_label'] = $purchase_lib->generateConfirmLabel(true);
        $purchase['shipped_label'] = $purchase_lib->generateShippedLabel();

        $data = [
            'purchase' => $purchase,
            'shipment' => $shipment,
            'products' => $products,
            'title' => '確認收貨',
            'view' => 'shipment/confirm',
        ];

        $this->_preload($data);
    }

    public function check_qty($i, $params)
    {
        $params = json_decode($params, true);
        $shipment_items = $params['shipment_items'];
        $products = $params['products'];
        $items = $params['items'];
        $error = '';

        foreach ($shipment_items as $shipment_item) {
            $product_id = $shipment_item['product_id'];
            if (!isset($products[$product_id]) || !isset($items[$product_id])) {
                $error = '輸入的貨品錯誤';
                break;
            }
        }

        if (!$error) {
            return true;
        } else {
            $this->form_validation->set_message('check_qty', $error);
            return false;
        }
    }


    public function cancel($shipment_id)
    {
        $shipment = $this->shipment_model
            ->where('shipout_retailer_id', $this->dealer['retailer_id'])
            ->get($shipment_id);

        if (!$shipment_id || !$shipment) {
            show_error('查無出貨資料');
        }

        if (!is_null($shipment['isConfirmed'])) {
            show_error('出貨已經確認不能取消');
        }

        $purchase = $this->purchase_model
            ->with_transfer_from()
            ->get($shipment['ship_id']);

        if (!$purchase) {
            show_error('查無出貨單資料');
        }

        //出貨扣庫恢復
        $this->stock_lib->shipout_rollback($shipment_id);

        $this->shipment_model->delete($shipment_id);
        $this->purchase_model->update(['isShipped' => 0, 'shipped_at' => null], ['id' => $purchase['id']]);

        if (!empty($purchase['transfer_from'])) {
            $transfer_shipment = $this->shipment_model
                ->where('shipment_id', $shipment_id)
                ->where('ship_type', 'purchase')
                ->where('ship_id', $purchase['transfer_from']['id'])
                ->get();
            if ($transfer_shipment) {
                $this->shipment_model->delete($transfer_shipment['id']);
                $this->purchase_model->update(['isShipped' => 0, 'shipped_at' => null], ['id' => $purchase['transfer_from']['id']]);
            }
        }

        redirect(base_url('/transfer/detail/' . $purchase['id']));
    }

    public function revise_edit($shipment_revise_id)
    {
        $shipment_revise = $this->shipment_revise_model
            ->get($shipment_revise_id);

        if (!$shipment_revise_id || !$shipment_revise) {
            show_error('查無銷貨異動資料');
        }

        if ($shipment_revise['isConfirmed']){
            show_error('銷貨異動資料已確認');
        }

        $shipment_id = $shipment_revise['shipment_id'];

        $shipment = $this->shipment_model
            ->with_purchase()
            ->with_items(['with' => ['relation' => 'product']])
            ->get($shipment_id);

        $transfer_shipment = [];
        if (!is_null($shipment['purchase']['transfer_id'])) {
            $transfer_shipment = $this->shipment_model
                ->with_revise()
                ->get($shipment['shipment_id']);
        }

        $_products = $this->shipment_expiration_model
            ->where('shipment_id', $shipment_id)
            ->get_all();

        $products = [];
        if ($_products){
            foreach ($_products as $p){
                if (!isset($products[$p['product_id']])){
                    $products[$p['product_id']] = [];
                }

                if (is_null($p['expired_at'])){
                    $p['expired_at'] = 0;
                    $this->shipment_revise_item_model->where('expired_at IS NULL', null, null, false, false, true);
                } else {
                    $this->shipment_revise_item_model->where('expired_at', $p['expired_at']);
                }

                $p['revise'] = $this->shipment_revise_item_model
                    ->where('shipment_revise_id', $shipment_revise_id)
                    ->where('product_id', $p['product_id'])
                    ->get();

                $products[$p['product_id']][] = $p;
            }
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('items', '數量', 'callback_check_qty[' . json_encode(['shipment_items' => $shipment['items'], 'products' => $products, 'items' => $this->input->post('items')]) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $items = (array)$this->input->post('items');
                $memo_pictures = empty($_FILES['memo_pictures']) ? [] : $_FILES['memo_pictures'];

                $isAllCorrect = true;

                $config['upload_path'] = FCPATH . 'uploads/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = 10000000; //10M
                $config['file_ext_tolower'] = true;
                $config['encrypt_name'] = true;
                $this->load->library('upload', $config);

                foreach ($shipment['items'] as $shipment_item) {
                    $product_id = $shipment_item['product_id'];
                    foreach ($products[$product_id] as $stock) {
                        $stock_qty = $stock['qty'];
                        $shipin_qty = $items[$product_id][$stock['expired_at']]['qty'];
                        if ($stock_qty != $shipin_qty) {
                            $isAllCorrect = false;
                        }
                    }
                }

                if ($isAllCorrect){
                    $this->purchase_model->update(['isRevised' => 0], ['id' => $shipment['ship_id']]);
                    $this->shipment_revise_model->delete($shipment_revise_id);
                    $this->stock_lib->shipin_confirm($shipment_id);
                    $this->purchase_model->checkCorrect($shipment['ship_id']);
                    if ($transfer_shipment) {
                        $this->purchase_model->update(['isRevised' => 0], ['id' => $transfer_shipment['ship_id']]);
                        $this->purchase_model->checkCorrect($transfer_shipment['ship_id']);
                    }
                } else {
                    $this->shipment_revise_item_model->where('shipment_revise_id', $shipment_revise_id)->delete();
                    if ($transfer_shipment && !empty($transfer_shipment['revise'])) {
                        $this->shipment_revise_item_model->where('shipment_revise_id', $transfer_shipment['revise']['id'])->delete();
                    }
                    foreach ($shipment['items'] as $shipment_item) {
                        $product_id = $shipment_item['product_id'];

                        foreach ($products[$product_id] as $stock) {
                            $memo_picture = empty($items[$product_id][$stock['expired_at']]['memo_file']) ? null : $items[$product_id][$stock['expired_at']]['memo_file'];
                            $shipin_qty = $items[$product_id][$stock['expired_at']]['qty'];

                            if ($memo_pictures && !empty($memo_pictures['size'][$product_id][$stock['expired_at']])) {
                                $_FILES['image']['name'] = $memo_pictures['name'][$product_id][$stock['expired_at']];
                                $_FILES['image']['type'] = $memo_pictures['type'][$product_id][$stock['expired_at']];
                                $_FILES['image']['tmp_name'] = $memo_pictures['tmp_name'][$product_id][$stock['expired_at']];
                                $_FILES['image']['error'] = $memo_pictures['error'][$product_id][$stock['expired_at']];
                                $_FILES['image']['size'] = $memo_pictures['size'][$product_id][$stock['expired_at']];

                                if ($this->upload->do_upload('image')) {
                                    $upload_data = $this->upload->data();
                                    $memo_picture = '/uploads/' . $upload_data['file_name'];
                                }
                            }

                            $memo = empty($items[$product_id][$stock['expired_at']]['memo']) ? '' : $items[$product_id][$stock['expired_at']]['memo'];

                            $this->shipment_revise_item_model->insert([
                                'shipment_revise_id' => $shipment_revise_id,
                                'product_id' => $product_id,
                                'expired_at' => $stock['expired_at'] ? $stock['expired_at'] : null,
                                'qty' => $shipin_qty,
                                'memo' => $memo,
                                'memo_file' => $memo_picture,
                            ]);

                            if ($transfer_shipment && !empty($transfer_shipment['revise'])) {
                                $this->shipment_revise_item_model->insert([
                                    'shipment_revise_id' => $transfer_shipment['revise']['id'],
                                    'product_id' => $product_id,
                                    'expired_at' => $stock['expired_at'] ? $stock['expired_at'] : null,
                                    'qty' => $shipin_qty,
                                    'memo' => $memo,
                                    'memo_file' => $memo_picture,
                                ]);
                            }
                        }
                    }
                }

                redirect(base_url('/purchase/detail/' . $shipment['ship_id']));
            }
        }

        $data = [
            'shipment' => $shipment,
            'products' => $products,
            'title' => '編輯銷貨異動',
            'view' => 'shipment/revise_edit',
        ];

        $this->_preload($data);
    }

    public function confirm_revise($shipment_revise_id)
    {
        $shipment_revise = $this->shipment_revise_model
            ->with_items()
            ->with_shipment(['with' => ['relation' => 'purchase']])
            ->get($shipment_revise_id);

        if (!$shipment_revise_id || !$shipment_revise) {
            show_error('查無銷貨異動資料');
        }

        if ($shipment_revise['isConfirmed']){
            show_error('銷貨異動資料已確認');
        }

        $shipment_id = $shipment_revise['shipment_id'];
        $shipment = $shipment_revise['shipment'];
        $purchase = $shipment['purchase'];
        $purchase_id = $shipment['ship_id'];

        if (!is_null($purchase['transfer_id'])) {
            show_error('轉單不能新增銷貨退回');
        }

        $transfer_shipment = $this->shipment_model
            ->with_purchase()
            ->with_revise()
            ->where('shipment_id', $shipment_id)
            ->get();

        $this->load->model('confirm_model');
        $this->confirm_model->confirmed('shipment_revise', $shipment_revise_id, 1, $this->dealer);
        $this->shipment_revise_model->update(['isConfirmed' => 1], ['id' => $shipment_revise_id]);
        $this->purchase_model->update(['isRevised' => 0], ['id' => $purchase_id]);
        $this->purchase_model->checkCorrect($purchase_id);

        if ($transfer_shipment && !empty($transfer_shipment['revise'])) {
            $this->confirm_model->confirmed('shipment_revise', $transfer_shipment['revise']['id'], 1, $this->dealer);
            $this->shipment_revise_model->update(['isConfirmed' => 1], ['id' => $transfer_shipment['revise']['id']]);
            $this->purchase_model->update(['isRevised' => 0], ['id' => $transfer_shipment['ship_id']]);
            $this->purchase_model->checkCorrect($transfer_shipment['ship_id']);
        }

        $new_shipment_id = $this->shipment_model->insert([
            'shipment_id' => $shipment_id,
            'ship_type' => 'purchase',
            'ship_id' => $purchase_id,
            'shipout_retailer_id' => $shipment['shipout_retailer_id'],
            'shipin_retailer_id' => $shipment['shipin_retailer_id'],
            'eta_at' => $shipment['eta_at'] ? $shipment['eta_at'] : null,
            'memo' => $shipment['memo'] ? $shipment['memo'] : null,
            'isConfirmed' => 1,
            'isRevised' => 1,
            'retailer_id' => $this->dealer['retailer_id'],
            'dealer_id' => $this->dealer['id'],
        ]);

        if ($transfer_shipment) {
            $new_transfer_shipment_id = $this->shipment_model->insert([
                'shipment_id' => $transfer_shipment['id'],
                'ship_type' => 'purchase',
                'ship_id' => $transfer_shipment['ship_id'],
                'shipout_retailer_id' => $transfer_shipment['shipout_retailer_id'],
                'shipin_retailer_id' => $transfer_shipment['shipin_retailer_id'],
                'eta_at' => $transfer_shipment['eta_at'] ? $transfer_shipment['eta_at'] : null,
                'memo' => $transfer_shipment['memo'] ? $transfer_shipment['memo'] : null,
                'isConfirmed' => 1,
                'isRevised' => 1,
                'retailer_id' => $this->dealer['retailer_id'],
                'dealer_id' => $this->dealer['id'],
            ]);
        }

        foreach ($shipment_revise['items'] as $item) {
            $this->shipment_item_model->insert([
                'shipment_id' => $new_shipment_id,
                'product_id' => $item['product_id'],
                'qty' => $item['qty'],
            ]);

            //紀錄產品有效期限
            $this->shipment_expiration_model->insert([
                'shipment_id' => $new_shipment_id,
                'product_id' => $item['product_id'],
                'expired_at' => $item['expired_at'] ? $item['expired_at'] : null,
                'qty' => $item['qty'],
            ]);

            if ($transfer_shipment) {
                $this->shipment_item_model->insert([
                    'shipment_id' => $new_transfer_shipment_id,
                    'product_id' => $item['product_id'],
                    'qty' => $item['qty'],
                ]);

                $this->shipment_expiration_model->insert([
                    'shipment_id' => $new_transfer_shipment_id,
                    'product_id' => $item['product_id'],
                    'expired_at' => $item['expired_at'] ? $item['expired_at'] : null,
                    'qty' => $item['qty'],
                ]);
            }
        }

        //原出貨恢復
        $this->stock_lib->shipout_rollback($shipment_id);

        //重新出貨扣庫
        $this->stock_lib->shipout_confirm($new_shipment_id);

        if ($transfer_shipment) {
            $this->stock_lib->shipin_confirm($new_transfer_shipment_id);
        } else {
            $this->stock_lib->shipin_confirm($new_shipment_id);
        }

        redirect(base_url('/transfer/detail/' . $purchase_id));
    }

    public function return_add($purchase_id)
    {
        $purchase = $this->purchase_model
            ->with_transfer_from()
            ->where('shipin_retailer_id', $this->dealer['retailer_id'])
            ->get($purchase_id);

        if (!$purchase) {
            show_error('查無進貨單資料');
        }

        if (!$purchase['isShipConfirmed']) {
            show_error('進貨單尚未收貨確認');
        }

        if (!empty($purchase['transfer_from'])) {
            show_error('轉單不能新增銷貨退回');
        }

        $shipment = $this->shipment_model
            ->with_items(['with' => ['relation' => 'product']])
            ->where('ship_type', 'purchase')
            ->where('ship_id', $purchase_id)
            ->where('isConfirmed', 1)
            ->order_by('id', 'desc')
            ->get();

        if (!$shipment) {
            show_error('查無銷貨單資料');
        }

        $_products = $this->shipment_expiration_model
            ->where('shipment_id', $shipment['id'])
            ->get_all();

        $products = [];
        if ($_products){
            foreach ($_products as $p){
                if (!isset($products[$p['product_id']])){
                    $products[$p['product_id']] = [];
                }
                $p['expired_at'] = is_null($p['expired_at']) ? 0 : $p['expired_at'];
                $products[$p['product_id']][] = $p;
            }
        }

        $shipment_items = [];
        if ($shipment['items']){
            foreach ($shipment['items'] as $p){
                $shipment_items[$p['product_id']] = $p;
            }
        }
        $shipment['items'] = $shipment_items;

        if ($this->input->post()) {
            $this->form_validation->set_rules('eta_at', '出貨日期', 'required|valid_date');
            $this->form_validation->set_rules('fare', '運費', 'required|integer|greater_than_equal_to[0]');

            $check_expired_options = [
                'shipment_items' => $shipment['items'],
                'products' => $products,
                'items' => $this->input->post('items'),
            ];

            $this->form_validation->set_rules('items', '出貨數量', 'callback_check_return_qty[' . json_encode($check_expired_options) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $new_shipment_id = $this->shipment_model->insert([
                    'ship_type' => 'purchase',
                    'ship_id' => $purchase_id,
                    'shipout_retailer_id' => $shipment['shipin_retailer_id'],
                    'shipin_retailer_id' => $shipment['shipout_retailer_id'],
                    'eta_at' => $this->input->post('eta_at'),
                    'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
                    'isReturn' => 1,
                    'retailer_id' => $this->dealer['retailer_id'],
                    'dealer_id' => $this->dealer['id'],
                ]);

                $this->purchase_model->update(['isReturn' => 1], ['id' => $purchase_id]);

                $transfer_purchase = [];
                if (!is_null($purchase['transfer_id'])){
                    $transfer_purchase = $this->purchase_model
                        ->get($purchase['transfer_id']);
                    if ($transfer_purchase) {
                        $new_transfer_shipment_id = $this->shipment_model->insert([
                            'shipment_id' => $new_shipment_id,
                            'ship_type' => 'purchase',
                            'ship_id' => $transfer_purchase['id'],
                            'shipout_retailer_id' => $transfer_purchase['retailer_id'],
                            'shipin_retailer_id' => $transfer_purchase['shipout_retailer_id'],
                            'eta_at' => $this->input->post('eta_at'),
                            'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
                            'isReturn' => 1,
                            'retailer_id' => $this->dealer['retailer_id'],
                            'dealer_id' => $this->dealer['id'],
                        ]);

                        $this->purchase_model->update(['isReturn' => 1], ['id' => $transfer_purchase['id']]);
                    }
                }


                $items = (array)$this->input->post('items');
                foreach ($items as $product_id => $expired_data) {
                    $item_qty = 0;
                    foreach ($expired_data as $expired_at => $qty) {
                        if ($qty > 0) {
                            $this->shipment_expiration_model->insert([
                                'shipment_id' => $new_shipment_id,
                                'product_id' => $product_id,
                                'expired_at' => $expired_at ? $expired_at : null,
                                'qty' => $qty,
                            ]);

                            if ($transfer_purchase && !empty($new_transfer_shipment_id)) {
                                $this->shipment_expiration_model->insert([
                                    'shipment_id' => $new_transfer_shipment_id,
                                    'product_id' => $product_id,
                                    'expired_at' => $expired_at ? $expired_at : null,
                                    'qty' => $qty,
                                ]);
                            }
                            $item_qty += $qty;
                        }
                    }

                    if ($item_qty > 0) {
                        $this->shipment_item_model->insert([
                            'shipment_id' => $new_shipment_id,
                            'product_id' => $product_id,
                            'qty' => $item_qty,
                        ]);

                        if ($transfer_purchase && !empty($new_transfer_shipment_id)) {
                            $this->shipment_item_model->insert([
                                'shipment_id' => $new_transfer_shipment_id,
                                'product_id' => $product_id,
                                'qty' => $item_qty,
                            ]);
                        }
                    }
                }

                //出貨扣庫
                $this->stock_lib->shipout_confirm($new_shipment_id);

                //運費
                $fare = $this->input->post('fare');
                if ($fare > 0) {
                    $this->load->model('expense_model');
                    $this->expense_model->insert([
                        'retailer_id' => $shipment['shipin_retailer_id'],
                        'event_type' => 'shipment',
                        'event_id' => $new_shipment_id,
                        'expense_type' => 'freight',
                        'price' => $fare,
                        'dealer_id' => $this->dealer['id'],
                    ]);
                }

                redirect(base_url('/purchase/detail/' . $purchase_id));
            }
        }

        $data = [
            'shipment' => $shipment,
            'products' => $products,
            'title' => '新增銷貨退回',
            'view' => 'shipment/return_add',
        ];

        $this->_preload($data);
    }

    public function check_return_qty($i, $params)
    {
        $params = json_decode($params, true);
        $shipment_items = (array)$params['shipment_items'];
        $products = (array)$params['products'];
        $items = (array)$params['items'];
        $error = '';

        if (!$items) {
            $error = '無輸入任何商品';
        } else {
            foreach ($items as $product_id => $expired_data) {
                if (!isset($products[$product_id]) || !isset($shipment_items[$product_id])) {
                    $error = '輸入的貨品錯誤';
                    break;
                }

                $shipping_qty = 0;
                foreach ($expired_data as $expired_at => $qty){
                    if ($qty > 0) {
                        foreach ($products[$product_id] as $p){
                            if ($p['expired_at'] == $expired_at){
                                if ($p['qty'] < $qty){
                                    $error = '銷貨退回商品數量大於原銷貨數量';
                                    break 3;
                                }
                                $shipping_qty += $qty;
                                break;
                            }
                        }
                    }
                }

                if ($shipment_items[$product_id]['qty'] < $shipping_qty){
                    $error = '銷貨退回商品總數大於原銷貨總數';
                    break;
                }
            }
        }

        if (!$error) {
            return true;
        } else {
            $this->form_validation->set_message('check_return_qty', $error);
            return false;
        }
    }

    public function confirm_return($shipment_id)
    {
        $shipment = $this->shipment_model
            ->with_purchase()
            ->where('ship_type', 'purchase')
            ->where('isReturn', 1)
            ->get($shipment_id);

        if (!$shipment_id || !$shipment) {
            show_error('查無收貨資料');
        }

        if ($shipment['isConfirmed']){
            show_error('已確認過銷貨退回資料');
        }

        $transfer_shipment = [];
        if (!is_null($shipment['purchase']['transfer_id'])) {
            show_error('轉單不能新增銷貨退回');
        } elseif (!is_null($shipment['shipment_id'])) {
            $transfer_shipment = $this->shipment_model
                ->where('ship_type', 'purchase')
                ->where('isReturn', 1)
                ->get($shipment['shipment_id']);
        }

        $this->load->model('confirm_model');
        $this->confirm_model->confirmed('shipment', $shipment_id, 1, $this->dealer);
        if ($transfer_shipment) {
            $this->confirm_model->confirmed('shipment', $transfer_shipment['id'], 1, $this->dealer);
        }

        $this->shipment_model->update(['isConfirmed' => 1], ['id' => $shipment_id]);
        $this->stock_lib->shipin_confirm($shipment_id);
        $this->purchase_model->update(['isReturn' => 0], ['id' => $shipment['ship_id']]);
        if ($transfer_shipment) {
            $this->shipment_model->update(['isConfirmed' => 1], ['id' => $transfer_shipment['id']]);
            $this->purchase_model->update(['isReturn' => 0], ['id' => $transfer_shipment['ship_id']]);
        }

        redirect(base_url('/transfer/detail/' . $shipment['ship_id']));
    }

    public function allowance_add($purchase_id)
    {
        $purchase = $this->purchase_model
            ->with_transfer_from()
            ->where('shipin_retailer_id', $this->dealer['retailer_id'])
            ->get($purchase_id);

        if (!$purchase) {
            show_error('查無進貨單資料');
        }

        if (!$purchase['isConfirmed']) {
            show_error('進貨單尚未確認');
        }

        if (!$purchase['isShipConfirmed']) {
            show_error('進貨單尚未收貨確認');
        }

        if (!$purchase['isPayConfirmed']) {
            show_error('進貨單尚未確認收款');
        }

        if (!empty($purchase['transfer_from'])) {
            show_error('轉單不能新增銷貨折讓');
        }

        $shipment = $this->shipment_model
            ->where('ship_type', 'purchase')
            ->where('ship_id', $purchase_id)
            ->where('isConfirmed', 1)
            ->order_by('id', 'desc')
            ->get();

        if (!$shipment) {
            show_error('查無銷貨單資料');
        }

        if ($this->input->post()) {
            $this->form_validation->set_rules('price', '銷貨折讓', 'required|integer|greater_than[0]');

            if ($this->form_validation->run() !== FALSE) {
                $this->load->model('payment_model');

                $this->payment_model->insert([
                    'pay_type' => 'shipment_allowance',
                    'pay_id' => $purchase_id,
                    'paid_retailer_id' => $purchase['shipout_retailer_id'],
                    'received_retailer_id' => $purchase['retailer_id'],
                    'price' => $this->input->post('price'),
                    'retailer_id' => $this->dealer['retailer_id'],
                    'dealer_id' => $this->dealer['id'],
                    'active' => 0,
                ]);

                $this->purchase_model->update(['isAllowance' => 1], ['id' => $purchase_id]);

                if (!is_null($purchase['transfer_id'])){
                    $transfer_purchase = $this->purchase_model
                        ->get($purchase['transfer_id']);
                    if ($transfer_purchase) {
                        $this->payment_model->insert([
                            'pay_type' => 'shipment_allowance',
                            'pay_id' => $transfer_purchase['id'],
                            'paid_retailer_id' => $transfer_purchase['shipout_retailer_id'],
                            'received_retailer_id' => $transfer_purchase['retailer_id'],
                            'price' => $this->input->post('price'),
                            'retailer_id' => $this->dealer['retailer_id'],
                            'dealer_id' => $this->dealer['id'],
                            'active' => 0,
                        ]);

                        $this->purchase_model->update(['isAllowance' => 1], ['id' => $transfer_purchase['id']]);
                    }
                }

                redirect(base_url('/purchase/detail/' . $purchase_id));
            }
        }

        $data = [
            'shipment' => $shipment,
            'title' => '新增銷貨折讓',
            'view' => 'shipment/allowance_add',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/libraries/MY_Form_validation.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {
    public function __construct($rules = array())
    {
        parent::__construct($rules);
    }

    public function valid_date($str) {
        if (($str = strtotime($str)) === FALSE) {
            $this->set_message('valid_date', '{field} 欄位必須是一個有效的日期');
            return FALSE;
        }

        return TRUE;
    }

    //驗證人員帳號是否重複
    public function valid_dealer_account($account){
        if ($account) {
            $this->CI->load->model('dealer_model','',TRUE);
            $results = $this->CI->dealer_model
                ->where('account', strtolower($account))
                ->get_all();
            if (!$results){
                return true;
            } else {
                $this->set_message('valid_dealer_account', '輸入的帳號已曾建立，請新增其他帳號');
                return false;
            }
        } else {
            $this->set_message('valid_dealer_account', '必須輸入帳號');
            return false;
        }
    }

    //驗證消費者電話是否重複
    public function valid_custom_phone($phone, $exclude_id = ''){
        if ($phone) {
            $this->CI->load->model('customer_model','',TRUE);
            $exclude_id = (int)$exclude_id;
            if ($exclude_id){
                $results = $this->CI->customer_model
                    ->where('phone', $phone)
                    ->where('id', '!=', $exclude_id)
                    ->get_all();
            } else {
                $results = $this->CI->customer_model
                    ->where('phone', $phone)
                    ->get_all();
            }
            if (!$results){
                return true;
            } else {
                $this->set_message('valid_custom_phone', '輸入的電話已建立，請新增其他電話');
                return false;
            }
        } else {
            $this->set_message('valid_custom_phone', '必須輸入電話');
            return false;
        }
    }
}<file_sep>/application/migrations/052_update_retailer_month_threshold.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_retailer_month_threshold extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_retailers', [
            'firstThreshold' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
                'after' => 'address',
            ],
            'options' => [
                'type' => 'TEXT',
                'null' => TRUE,
                'after' => 'isLocked',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_retailers', 'firstThreshold');
        $this->dbforge->drop_column('olive_retailers', 'options');
    }
}<file_sep>/application/views/customer/import.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">匯入舊有會員資訊
                <div class="float-right">
                    <a href="<?= base_url('/files/template.xls') ?>" class="btn btn-info mr-2"><i class="fas fa-download"></i> 匯入範本</a>
                </div>
            </h1>

            <form method="post" enctype="multipart/form-data">
                <?php if (validation_errors() || $error) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                        <?= $error ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label class="font-weight-bold">上傳檔案</label>
                    <input type="file" name="oldfile" required accept="application/vnd.ms-excel" class="form-control-file" />
                </div>

                <div class="form-group">
                    <input type="submit" class="btn btn-success" value="上傳"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/controllers/Capital_retailer_qualification.php
<?php

class Capital_retailer_qualification extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->helper('data_format');
        $this->load->model('retailer_model');
        $this->load->model('retailer_level_model');
        $this->load->model('retailer_qualification_model');

        $this->session->set_userdata('return_page', base_url('/capital_retailer/overview'));
    }

    public function overview($retailer_id)
    {
        $retailer = $this->retailer_model
            ->get($retailer_id);

        if (!$retailer_id || !$retailer) {
            show_error('查無經銷單位資料！');
        }

        $total_levels_count = $this->retailer_level_model
            ->count_rows();

        $levels = $this->retailer_level_model
            ->with_type()
            ->order_by('retailer_level_type_id', 'asc')
            ->order_by('code', 'asc')
            ->paginate(20, $total_levels_count);

        if ($levels){
            foreach ($levels as $key => $level){
                $qualification = $this->retailer_qualification_model
                    ->where('retailer_id', $retailer_id)
                    ->where('retailer_level_id', $level['id'])
                    ->get();
                $levels[$key]['qualification'] = empty($qualification) ? 0 : 1;
            }
        }

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_retailer_qualification', 'edit')){
            $authority['edit'] = true;
        }

        $data = [
            'retailer' => $retailer,
            'levels' => $levels,
            'pagination' => $this->retailer_level_model->all_pages,
            'authority' => $authority,
            'title' => '經銷拓展資格',
            'view' => 'capital/retailer/qualification/overview',
        ];

        $this->_preload($data);
    }

    public function edit($retailer_id, $level_id)
    {
        $retailer = $this->retailer_model
            ->get($retailer_id);

        if (!$retailer_id || !$retailer) {
            show_error('查無經銷單位資料！');
        }

        $level = $this->retailer_level_model
            ->with_type()
            ->get($level_id);

        if (!$level_id || !$level) {
            show_error('查無經銷規則資料');
        }

        if ($this->input->post()) {
            $this->retailer_qualification_model
                ->where('retailer_id', $retailer_id)
                ->where('retailer_level_id', $level_id)
                ->delete();

            if ($this->input->post('qualification')){
                $this->retailer_qualification_model->insert([
                    'retailer_id' => $retailer_id,
                    'retailer_level_id' => $level_id,
                ]);
            }

            redirect(base_url('/capital_retailer_qualification/overview/' . $retailer_id));
        }

        $qualification = $this->retailer_qualification_model
            ->where('retailer_id', $retailer_id)
            ->where('retailer_level_id', $level_id)
            ->get();

        $data = [
            'retailer' => $retailer,
            'level' => $level,
            'qualification' => $qualification,
            'title' => '編輯經銷拓展資格',
            'view' => 'capital/retailer/qualification/edit',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/models/Recommend_template_model.php
<?php

class Recommend_template_model extends MY_Model
{
    public $table = 'olive_recommend_templates';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_many['recommends'] = array('Recommend_model', 'recommend_template_id', 'id');
    }
}

?>
<file_sep>/application/migrations/032_update_payment.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_payment extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_payments', [
            'active' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'memo',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_payments', 'active');
    }
}<file_sep>/application/controllers/Confirm.php
<?php

class Confirm extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!$this->dealer = $this->authentic->isLogged()) {
            redirect(base_url('/auth/login'));
        }

        $this->load->model('confirm_model');
        $this->load->helper('data_format');

        $this->session->set_userdata('return_page', base_url('/confirm/overview'));
    }

    public function overview($confirm)
    {
        $confirm_array = explode('_', $confirm);
        if (!$confirm_array){
            show_error('查無確認資料');
        }

        $confirm_type = $confirm_array[0];
        $confirm_id = $confirm_array[1];
        $total_confirms_count = $this->confirm_model
            ->where('confirm_type', $confirm_type)
            ->where('confirm_id', $confirm_id)
            ->count_rows();

        if (!$total_confirms_count) {
            show_error('查無確認資料');
        }

        $confirms = $this->confirm_model
            ->with_retailer()
            ->where('confirm_type', $confirm_type)
            ->where('confirm_id', $confirm_id)
            ->order_by('id', 'desc')
            ->paginate(20, $total_confirms_count);

        $data = [
            'confirms' => $confirms,
            'pagination' => $this->confirm_model->all_pages,
            'title' => '確認紀錄列表',
            'view' => 'confirm/overview',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/migrations/009_add_shipment.php
<?php
//經銷商訂貨單產品
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_shipment extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'ship_type' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => TRUE,
            ],
            'ship_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'shipout_retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'shipin_retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'totalQty' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'subtotal' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'total' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'eta_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'memo' => [
                'type' => 'TEXT',
                'null' => TRUE,
            ],
            'isConfirmed' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'retailer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'dealer_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_shipments');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_shipments');
    }
}<file_sep>/application/migrations/035_update_order.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_order extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_orders', [
            'couponNum' => [
                'type' => 'VARCHAR',
                'constraint' => 30,
                'null' => TRUE,
                'after' => 'orderNum',
            ],
            'totalDiscount' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'subtotal',
            ],
            'totalReachDiscount' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'totalDiscount',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_orders', 'couponNum');
        $this->dbforge->drop_column('olive_orders', 'totalDiscount');
        $this->dbforge->drop_column('olive_orders', 'totalReachDiscount');
    }
}<file_sep>/application/helpers/data_format_helper.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

if (!function_exists('confirmStatus')) {
    function confirmStatus($key = false, $memo = '', $agree_text='同意', $reject_text='拒絕')
    {
        if (is_null($key)){
            return '<span class="badge badge-light" data-toggle="tooltip" data-html="true" title="' . $memo . '">未確認</span>';
        } elseif ($key) {
            return '<span class="badge badge-success" data-toggle="tooltip" data-html="true" title="' . $memo . '">' . $agree_text . '</span>';
        } else {
            return '<span class="badge badge-danger" data-toggle="tooltip" data-html="true" title="' . $memo . '">' . $reject_text . '</span>';
        }
    }
}

if (!function_exists('eventStatus')) {
    function eventStatus($key = false)
    {
        if ($key) {
            return '<span class="badge badge-success">是</span>';
        } else {
            return '<span class="badge badge-danger">否</span>';
        }
    }
}

if (!function_exists('yesno')) {
    function yesno($key = false)
    {
        if ($key) {
            return '<span class="badge badge-success">是</span>';
        } else {
            return '<span class="badge badge-danger">否</span>';
        }
    }
}

if (!function_exists('gender')) {
    function gender($key = false)
    {
        if ($key == '1') {
            return '男';
        } elseif ($key === '0') {
            return '女';
        }

        return '';
    }
}

if (!function_exists('paymentType')) {
    function paymentType($key = false)
    {
        if ($key) {
            $key = (int)$key;
            switch ($key) {
                case 1:
                    return '現金付款';
                    break;
                case 2:
                    return '匯款';
                    break;
                default:
                    return '';
                    break;
            }
        } else {
            return [
                1 => '現金付款',
                2 => '匯款',
            ];
        }
    }
}


<file_sep>/application/views/shipment/return_add.php
<div class="container">
    <h1 class="mb-4">新增銷貨退回</h1>

    <form id="returnForm" method="post">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group">
            <label class="font-weight-bold">是否同時寄出商品</label>
            <div>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" name="yesno" id="yesno_1" value="1" required>
                    <label class="form-check-label" for="yesno_1">是</label>
                </div>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" name="yesno" id="yesno_0" value="0">
                    <label class="form-check-label" for="yesno_0">否</label>
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">出貨日期</label>
            <input type="date" name="eta_at" class="form-control"
                   value="<?= set_value('eta_at', date('Y-m-d')) ?>" required />
        </div>

        <div class="form-group">
            <label class="font-weight-bold">支付運費單位</label>
            <div>出貨方</div>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">運費</label>
            <input type="number" name="fare" class="form-control text-right"
                   value="<?= set_value('fare', 0) ?>" required/>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">出貨方之備註</label>
            <textarea rows="5" name="memo" class="form-control"><?= set_value('memo') ?></textarea>
        </div>

        <h4 class="my-4 text-center">出貨內容及有效期限</h4>
        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <td>貨品名稱</td>
                <td>到期日</td>
                <td>銷貨數量</td>
                <td>退回數量</td>
            </tr>
            <?php
            if ($shipment['items']) {
                foreach ($shipment['items'] as $product_id => $shipment_item) {
                    if (!isset($products[$product_id])){
                        continue;
                    }
                    $product_row = count($products[$product_id]);
                    ?>
                    <tr>
                        <td rowspan="<?=$product_row?>" class="align-middle"><?= $shipment_item['product']['pdName'] . $shipment_item['product']['intro2'] ?></td>
                        <?php
                        foreach ($products[$product_id] as $key => $product){
                            if ($key > 0){
                                echo '</tr><tr>';
                            }
                            ?>
                            <td class="align-middle">
                                <?= $product['expired_at'] ? $product['expired_at'] : '未標示'?>
                            </td>
                            <td class="align-middle text-right"><?= number_format($product['qty']) ?></td>
                            <td class="align-middle">
                                <input type="number" class="itemQty form-control text-right" name="items[<?=$product_id?>][<?=$product['expired_at']?>]" max="<?=$product['qty']?>" min="0" value="0" />
                            </td>
                        <?php
                        }
                        ?>
                    </tr>
                    <?php
                }
            }
            ?>
        </table>

        <div class="form-group d-flex justify-content-between">
            <a href="<?= base_url('/purchase/detail/' . $shipment['ship_id']) ?>" class="btn btn-secondary">取消</a>
            <input type="submit" class="btn_submit btn btn-success" value="送出銷貨退回"/>
        </div>
    </form>
</div>


<script>
    $(document).ready(function () {
        check_ship();

        $('input[name="yesno"]').change(function () {
            check_ship();
        });

        function check_ship() {
            if ($('input[name="yesno"]:checked').val() == 1) {
                $('.btn_submit').removeClass('d-none');
            } else {
                $('.btn_submit').addClass('d-none');
            }
        }

        $("#returnForm").submit(function (e) {
            if ($('input[name="yesno"]:checked').val() != 1) {
                return false;
            }

            var totalQty = 0;
            $('#returnForm input.itemQty').each(function () {
                totalQty += parseInt($(this).val()) || 0;
            });

            if (totalQty == 0) {
                alert('請至少退回一樣商品！');
                return false;
            }
        });
    });
</script><file_sep>/application/models/Purchase_defect_model.php
<?php

class Purchase_defect_model extends MY_Model
{
    public $table = 'olive_purchase_defects';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
        $this->has_one['item'] = array('foreign_model' => 'Purchase_item_model', 'foreign_table' => 'olive_purchase_items', 'foreign_key' => 'id', 'local_key' => 'purchase_item_id');
        $this->has_one['expense'] = array('foreign_model' => 'Expense_model', 'foreign_table' => 'olive_expenses', 'foreign_key' => 'event_id', 'local_key' => 'id');
    }

    public function getTransferDefect($defect_id, $isTransfer = false)
    {
        $transfer_purchase_id = '';
        if (!$isTransfer) {
            $defect = $this
                ->with_purchase()
                ->with_item()
                ->get($defect_id);
            if ($defect && $defect['purchase'] && $defect['item'] && !is_null($defect['purchase']['transfer_id'])) {
                $transfer_purchase_id = $defect['purchase']['transfer_id'];
                $product_id = $defect['item']['product_id'];
            }
        } else {
            $defect = $this
                ->with_purchase(['with' => ['relation' => 'transfer_from']])
                ->with_item()
                ->get($defect_id);
            if ($defect && $defect['purchase'] && $defect['item'] && $defect['purchase']['transfer_from']) {
                $transfer_purchase_id = $defect['purchase']['transfer_from']['id'];
                $product_id = $defect['item']['product_id'];
            }
        }

        if ($transfer_purchase_id) {
            $this->load->model('purchase_item_model');
            $transfer_purchase_item = $this->purchase_item_model->getPurchaseItemOfId($transfer_purchase_id, $product_id);

            if ($transfer_purchase_item && $transfer_purchase_item['defect']) {
                return $transfer_purchase_item;
            }
        }

        return false;
    }
}

?>
<file_sep>/application/migrations/017_add_commission.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_commission extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'commission_type' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
                'null' => TRUE,
            ],
            'commission_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'purchase_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'total' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_commissions');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_commissions');
    }
}<file_sep>/application/migrations/060_add_shipment_expiration.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_shipment_expiration extends CI_Migration
{
    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'shipment_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'product_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'expired_at' => [
                'type' => 'date',
                'null' => TRUE,
            ],
            'qty' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'created_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'updated_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ],
            'deleted_at' => [
                'type' => 'timestamp',
                'null' => TRUE,
            ]
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_shipment_expirations');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_shipment_expirations');
    }
}<file_sep>/application/views/capital/customer_level/overview.php
<div class="container">
    <h1 class="mb-4">會員資格管理</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">名稱</th>
            <th class="text-center">折扣</th>
            <th class="text-center">說明</th>
            <th></th>
        </tr>
        <?php
        if ($levels) {
            foreach ($levels as $level) {
                ?>
                <tr>
                    <td class="text-center"><?= $level['title'] ?></td>
                    <td class="text-center"><?= $level['discount'] . '%' ?></td>
                    <td><?= $level['description'] ?></td>
                    <td class="text-center">
                        <?php if (!empty($authority['edit'])){ ?>
                        <div class="btn-group" role="group">
                            <a class="btn btn-info btn-sm" href="<?= base_url('/capital_customer_level/edit/' . $level['id']) ?>">編輯</a>
                        </div>
                        <?php } ?>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="4" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>
</div><file_sep>/application/migrations/034_update_coupon.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_coupon extends CI_Migration
{

    public function up()
    {
        $this->dbforge->drop_column('olive_coupons', 'receive_qty');
        $this->dbforge->drop_column('olive_coupons', 'issue_qty');
        $this->dbforge->drop_column('olive_coupons', 'approve_qty');

        $this->dbforge->add_column('olive_coupons', [
            'qty' => [ //領用張數
                'type' => 'INT',
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'coupon_month',
            ],
            'first_couponNum' => [
                'type' => 'VARCHAR',
                'constraint' => 30,
                'null' => TRUE,
                'after' => 'qty',
            ],
            'last_couponNum' => [
                'type' => 'VARCHAR',
                'constraint' => 30,
                'null' => TRUE,
                'after' => 'first_couponNum',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_coupons', 'qty');
        $this->dbforge->drop_column('olive_coupons', 'first_couponNum');
        $this->dbforge->drop_column('olive_coupons', 'last_couponNum');

        $this->dbforge->add_column('olive_coupons', [
            'receive_qty' => [ //領用張數
                'type' => 'INT',
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'coupon_month',
            ],
            'issue_qty' => [ //發放張數
                'type' => 'INT',
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'receive_qty',
            ],
            'approve_qty' => [ //核定張數
                'type' => 'INT',
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'issue_qty',
            ],
        ]);
    }
}<file_sep>/application/models/Order_return_item_model.php
<?php

class Order_return_item_model extends MY_Model
{
    public $table = 'olive_order_return_items';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = false;
        $this->soft_deletes = false;
        $this->return_as = 'array';

        $this->has_one['order_return'] = array('foreign_model' => 'Order_return_model', 'foreign_table' => 'olive_order_returns', 'foreign_key' => 'id', 'local_key' => 'order_return_id');
        $this->has_one['product'] = array('foreign_model'=>'Product_model','foreign_table'=>'product','foreign_key'=>'pdId','local_key'=>'product_id');
    }
}

?>
<file_sep>/application/views/recommend_template/inside/edit.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">修改定案之推薦函</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <div class="form-group">
                    <label>內容</label>
                    <textarea class="form-control" name="content" rows="10" required><?= set_value('content', $template['content']) ?></textarea>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/recommend_template/inside')?>" class="btn btn-secondary">不儲存</a>
                    <input type="submit" class="btn btn-success" value="儲存"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/libraries/Authentic.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Authentic
{
    var $CI;
    var $dealer = [];

    public function __construct()
    {
        $this->CI =& get_instance();

        if ($this->CI->session->userdata('dealer') !== false) {
            $dealer_info = $this->CI->session->userdata('dealer');
            $this->dealer = $dealer_info;
        }
    }

    public function authenticate($account, $password)
    {
        $password = $<PASSWORD>($password);
        $time = date("Y-m-d H:i:s");

        $this->CI->load->model('dealer_model');
        $result = $this->CI->dealer_model
            ->where('account', $account)
            ->where('password', $password)
            ->with_retailer(['with' => [['relation' => 'sales_retailer'], ['relation' => 'sales_dealer']]])
            ->get();

        if ($result) {
            $level = [];
            if (!empty($result['retailer']['retailer_level_id'])) {
                $this->CI->load->model('retailer_level_model');
                $retailer_level = $this->CI->retailer_level_model
                    ->with_type()
                    ->get($result['retailer']['retailer_level_id']);

                $level = [
                    'discount' => $retailer_level['discount'],
                    'discount_text' => $retailer_level['discount'] . '%',
                    'title' => $retailer_level['type']['title'],
                    'type_id' => $retailer_level['type']['id'],
                    'type' => $retailer_level['type']['type'],
                    'code' => $retailer_level['code'],
                    'firstThreshold' => $retailer_level['firstThreshold'],
                    'monthThreshold' => $retailer_level['monthThreshold'],
                ];

                //經銷有最低訂購金額，超過一個月沒有超過門檻停用帳號
                $this->CI->load->library('purchase_lib');
                $dealer_total_purchases = $this->CI->purchase_lib->getRetailerTotalPurchases($result['retailer_id']);
                if ($dealer_total_purchases) {
                    $next_month_first_day = date('Y-m-d', strtotime('first day of next month ' . $dealer_total_purchases['first_at']));
                    $first_time_month_diff = $this->CI->purchase_lib->get_month_diff($next_month_first_day);
                    if ($first_time_month_diff > 1 && $retailer_level['monthThreshold'] > ($dealer_total_purchases['total'] - $dealer_total_purchases['first_total'])){ //超過一個月進貨沒有到額度
                        $now = date('Y-m-d H:i:s');
                        $this->CI->load->model('retailer_model');
                        $this->CI->retailer_model->update(['disabled_at' => $now], ['id' => $result['retailer_id']]);
                        $result['retailer']['disabled_at'] = $now;
                    }
                }
            }

            $this->dealer = [
                'id' => $result['id'],
                'retailer_id' => $result['retailer_id'],
                'retailer_role_id' => $result['retailer']['retailer_role_id'],
                'company' => $result['retailer']['company'],
                'invoice_title' => $result['retailer']['invoice_title'],
                'identity' => $result['retailer']['identity'],
                'contact_dealer_id' => $result['retailer']['contact_dealer_id'],
                'contact' => '',
                'contactNum' => '',
                'phone' => $result['retailer']['phone'],
                'altPhone' => $result['retailer']['altPhone'],
                'address' => $result['retailer']['address'],
                'hasStock' => $result['retailer']['hasStock'],
                'totalStock' => $result['retailer']['totalStock'],
                'isAllowBulk' => $result['retailer']['isAllowBulk'],
                'eta_days' => $result['retailer']['eta_days'],
                'disabled' => is_null($result['retailer']['disabled_at']) ? 0 : 1,
                'name' => $result['name'],
                'retailer_group_id' => $result['retailer_group_id'],
                'account' => $result['account'],
                'gender' => $result['gender'],
                'level' => $level,
                'sales_retailer' => $result['retailer']['sales_retailer'], //輔銷單位
                'sales_dealer' => $result['retailer']['sales_dealer'], //輔銷人
                'retailers' => [],
            ];

            //本單位的聯絡人資料
            if ($result['retailer']['contact_dealer_id']) {
                $contact_dealer = $this->CI->dealer_model
                    ->get($result['retailer']['contact_dealer_id']);
                if ($contact_dealer) {
                    $this->dealer['contact'] = $contact_dealer['name'];
                    $this->dealer['contactNum'] = $contact_dealer['account'];
                }
            }

            //取得本單位的下屬單位
            $this->CI->load->model('retailer_relationship_model');
            $retailers = $this->CI->retailer_relationship_model
                ->with_retailer()
                ->where('relation_retailer_id', $this->dealer['retailer_id'])
                ->where('relation_type', 'supervisor')
                ->get_all();
            if ($retailers) {
                foreach ($retailers as $retailer) {
                    array_push($this->dealer['retailers'], $retailer['id']);
                }
            }

            $this->CI->session->set_userdata('dealer', $this->dealer);

            $this->CI->load->model('dealer_history_model');
            $this->CI->dealer_history_model
                ->insert([
                    'IP' => $this->CI->input->ip_address(),
                    'stName' => $account,
                    'LoginTime' => $time,
                    'stId_link' => $result['id'],
                    'SID' => $this->CI->session->session_id,
                ]);
            return true;
        } else {
            $this->CI->load->model('bad_login_model');
            $this->CI->bad_login_model
                ->insert([
                    'account' => $account,
                    'ip' => $this->CI->input->ip_address(),
                    'btime' => $time,
                ]);
            $this->dealer = [];
            $this->CI->session->unset_userdata('dealer');
            return false;
        }
    }

    public function check_password($password)
    {
        if ($this->dealer) {
            $password = $this->_mix($password);

            $this->CI->load->model('dealer_model');
            $result = $this->CI->dealer_model
                ->where('password', $password)
                ->get($this->dealer['id']);

            if ($result) {
                return true;
            }
        }

        return false;
    }

    public function logout()
    {
        $this->CI->load->model('dealer_history_model');

        $dealer_history = $this->CI->dealer_history_model
            ->where('SID', $this->CI->session->userdata('session_id'))
            ->order_by('autoid', 'DESC')
            ->get();
        if ($dealer_history) {
            $this->CI->dealer_history_model
                ->update(['LogoutTime' => date("Y-m-d H:i:s")], ['autoid' => $dealer_history['autoid']]);
        }

        $this->dealer = [];
        $this->CI->session->unset_userdata('dealer');
        $this->CI->session->unset_userdata('guest');
        $this->CI->session->sess_destroy();
    }

    public function isLogged()
    {
        return $this->dealer;
    }

    public function _mix($hash)
    {
        $hash = md5($hash);
        return substr($hash, 10) . substr($hash, 0, 6);
    }

    public function authority($classname, $methodname = 'index')
    {
        if (!$classname) {
            return false;
        }

        if (!$this->dealer) {
            return false;
        }

        $this->CI->load->model('privilege_model');
        $privileges = $this->CI->privilege_model
            ->where('classname', $classname)
            ->get_all();

        $privilege_error = true;
        if ($privileges) {
            foreach ($privileges as $privilege){
                if ($privilege['methodname'] == $methodname){
                    $rules = unserialize($privilege['rules']);
                    if ($rules) {
                        if (!empty($rules[$this->dealer['retailer_group_id']])) {
                            $privilege_error = false;
                        }
                    }
                    break;
                }
            }

        }

        if ($privilege_error) {
            return false;
        } else {
            return true;
        }
    }
}

?><file_sep>/application/migrations/013_add_purchase_item.php
<?php
//經銷商訂貨單產品
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_purchase_item extends CI_Migration {

    public function up()
    {
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'purchase_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'product_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'price' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'qty' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'subtotal' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'discount' => [
                'type' => 'INT',
                'constraint' => 3,
                'unsigned' => TRUE,
                'default' => 100,
            ],
            'total' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_purchase_items');

        //缺貨
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'purchase_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'purchase_item_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'qty' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'supple_qty' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'isSupple' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'refund' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'isRefund' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'memo' => [
                'type' => 'TEXT',
                'null' => TRUE,
            ],
            'picture' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
            ],
            'import_method' => [
                'type' => 'tinyint',
                'constraint' => 2,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'export_response' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_purchase_shortages');

        //瑕疵品
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'purchase_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'purchase_item_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'qty' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'supple_qty' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'isSupple' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'refund' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'isRefund' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'memo' => [
                'type' => 'TEXT',
                'null' => TRUE,
            ],
            'picture' => [
                'type' => 'VARCHAR',
                'constraint' => 200,
                'null' => TRUE,
            ],
            'import_method' => [
                'type' => 'tinyint',
                'constraint' => 2,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
            'export_response' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_purchase_defects');

        //退貨
        $this->dbforge->add_field([
            'id' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
            ],
            'purchase_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'purchase_item_id' => [
                'type' => 'INT',
                'unsigned' => TRUE,
            ],
            'qty' => [
                'type' => 'INT',
                'constraint' => 10,
                'unsigned' => TRUE,
                'default' => 0,
            ],
            'isReturn' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'null' => TRUE,
            ],
        ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('olive_purchase_returns');
    }

    public function down()
    {
        $this->dbforge->drop_table('olive_purchase_items');
        $this->dbforge->drop_table('olive_purchase_shortages');
        $this->dbforge->drop_table('olive_purchase_defects');
        $this->dbforge->drop_table('olive_purchase_returns');
    }
}<file_sep>/application/models/Retailer_group_model.php
<?php

class Retailer_group_model extends MY_Model
{
    public $table = 'olive_retailer_groups';
    public $primary_key = 'id';

    function __construct()
    {
        parent::__construct();

        $this->timestamps = true;
        $this->soft_deletes = true;
        $this->return_as = 'array';

        $this->has_one['role'] = array('foreign_model' => 'Retailer_role_model', 'foreign_table' => 'olive_retailer_roles', 'foreign_key' => 'id', 'local_key' => 'retailer_role_id');
        $this->has_one['level_type'] = array('foreign_model' => 'Retailer_level_type_model', 'foreign_table' => 'olive_retailer_level_types', 'foreign_key' => 'id', 'local_key' => 'retailer_level_type_id');
        $this->has_many['dealers'] = array('Dealer_model', 'retailer_group_id', 'id');
    }

    public function getGroupSelect($retailer_role_id, $retailer_level_type_id = null)
    {
        if ($retailer_level_type_id){
            $this->where('retailer_level_type_id', $retailer_level_type_id);
        }
        $_groups = $this
            ->where('retailer_role_id', $retailer_role_id)
            ->get_all();
        $groups = [];
        if ($_groups) {
            foreach ($_groups as $group) {
                $groups[$group['id']] = $group['title'];
            }
        }
        return $groups;
    }
}

?>
<file_sep>/application/views/shipment/add.php
<div class="container">
    <h1 class="mb-4">新增出貨通知</h1>

    <form method="post">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group">
            <label class="font-weight-bold">收貨對象</label>
            <div><?= $purchase['shipin_retailer']['invoice_title'] ?></div>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">收貨地址</label>
            <td>
                <?php
                echo $purchase['shipin_address'];
                if (!$purchase['isMatchBox']){
                    echo '<div class="text-danger">取貨方式限定親自至輔銷單位取貨</div>';
                }
                ?>
            </td>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">是否同時寄出商品</label>
            <div>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" name="yesno" id="yesno_1" value="1" required>
                    <label class="form-check-label" for="yesno_1">是</label>
                </div>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" name="yesno" id="yesno_0" value="0">
                    <label class="form-check-label" for="yesno_0">否</label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="font-weight-bold">出貨日期</label>
            <input type="date" name="eta_at" class="form-control"
                   value="<?= set_value('eta_at', $eta_limit['start']) ?>" min="<?= $eta_limit['start'] ?>"
                   max="<?= $eta_limit['end'] ?>" required/>
            <small class="text-mute">出貨期限為<?= $eta_limit['end'] ?></small>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">支付運費單位</label>
            <div>出貨方</div>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">運費</label>
            <input type="number" name="fare" class="form-control text-right"
                   value="<?= set_value('fare', 0) ?>" required/>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">出貨方之備註</label>
            <textarea rows="5" name="memo" class="form-control"><?= set_value('memo') ?></textarea>
        </div>

        <h4 class="my-4 text-center">出貨內容及有效期限</h4>
        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <td>貨品名稱</td>
                <td>訂購數量</td>
                <td>庫存到期日</td>
                <td>庫存數量</td>
                <td>出貨數量</td>
            </tr>
            <?php
            if ($products) {
                foreach ($products as $product_id => $product) {
                    $stock_row = count($product['stocks']);
                    ?>
                    <tr>
                        <td rowspan="<?=$stock_row?>" class="align-middle"><?= $product['name'] ?></td>
                        <td rowspan="<?=$stock_row?>" class="align-middle text-right"><?= number_format($product['qty']) ?></td>
                        <?php if (empty($product['stocks'])){ ?>
                            <td class="align-middle"></td>
                            <td class="align-middle">無庫存</td>
                            <td class="align-middle text-danger item_shortage">庫存數量不足以出貨</td>
                            <?php
                        } else {
                            $product_qty = $product['qty'];
                            foreach ($product['stocks'] as $k => $stock) {
                                $qty = min($product_qty, $stock['stock']);

                                if ($k > 0){
                                    echo '</tr><tr>';
                                }
                                ?>
                                <td class="align-middle"><?= $stock['expired_at'] ? $stock['expired_at'] : '未標示' ?></td>
                                <td class="align-middle text-right"><?= number_format($stock['stock']) ?></td>
                                <td class="align-middle">
                                    <input type="number" class="form-control text-right" name="items[<?=$product_id?>][<?=$stock['expired_at']?>]" max="<?=$product['qty']?>" min="0" value="<?=$qty?>" />
                                </td>
                                <?php
                                if ($product_qty == $qty) {
                                    $product_qty = 0;
                                } else {
                                    $product_qty -= $qty;
                                }
                            }
                        }
                        ?>
                    </tr>
                    <?php
                }
            }
            ?>
        </table>

        <div class="form-group d-flex justify-content-between">
            <a href="<?= base_url('/transfer/detail/' . $purchase['id']) ?>" class="btn btn-secondary">取消</a>
            <input type="submit" class="btn_submit btn btn-success" value="送出已出貨訊息"/>
        </div>
    </form>
</div>


<script>
    $(document).ready(function () {
        showSubmit();

        $('input[name="yesno"]').change(function () {
            showSubmit();
        });

        function showSubmit() {
            var checkShip = check_ship();
            var checkShortage = check_shortage();
            if (checkShip && checkShortage){
                $('.btn_submit').removeClass('d-none');
            } else {
                $('.btn_submit').addClass('d-none');
            }
        }

        function check_ship() {
            if ($('input[name="yesno"]:checked').val() == 1) {
                return true;
            } else {
                return false;
            }
        }

        function check_shortage() {
            if ($('.item_shortage').length > 0){
                return false;
            } else {
                return true;
            }
        }

        $("#purchaseForm").submit(function (e) {
            if ($('input[name="yesno"]:checked').val() != 1) {
                return false;
            }
        });
    });
</script><file_sep>/application/controllers/Stock_counting.php
<?php

class Stock_counting extends MY_Controller
{
    protected $dealer, $counting_reason;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || !$this->dealer['hasStock']) {
            redirect(base_url('/'));
        }

        $this->load->model('stock_model');
        $this->load->model('stock_counting_model');
        $this->load->model('product_model');

        $this->counting_reason = [
            'M' => '月盤點',
            'P' => '總部不定期季盤點',
            'E' => '其他事由',
        ];

        $this->session->set_userdata('return_page', base_url('/stock_counting/index'));
    }

    public function index()
    {
        //權限設定
        $authority = array();
        if ($this->authentic->authority('stock_counting', 'set_print')){
            $authority['print'] = true;
        }
        if ($this->authentic->authority('stock_counting', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('stock_counting', 'overview')){
            $authority['overview'] = true;
        }

        $data = [
            'authority' => $authority,
            'title' => '盤點作業',
            'view' => 'stock_counting/index',
        ];

        $this->_preload($data);
    }

    public function set_print()
    {
        $products = $this->product_model->getUnitProductStocks($this->dealer['retailer_id']);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('stock_counting', 'process_print')){
            $authority['print'] = true;
        }

        $data = [
            'counting_reason' => $this->counting_reason,
            'products' => $products,
            'authority' => $authority,
            'title' => '「盤點清冊」下載',
            'view' => 'stock_counting/set_print',
        ];

        $this->_preload($data);
    }

    public function process_print()
    {
        $counting_reason = $this->input->get('counting_reason');
        if (!$counting_reason || !in_array($counting_reason, array_keys($this->counting_reason))){
            show_error('盤點事由未填寫');
        }
        $products = $this->product_model->getUnitProductStocks($this->dealer['retailer_id']);

        $data = [
            'counting_reason' => $this->counting_reason[$counting_reason],
            'products' => $products,
            'title' => '列印「盤點清冊」',
            'view' => 'stock_counting/process_print',
        ];

        $this->_preload($data);
    }

    public function overview()
    {
        $total_countings_count = $this->stock_counting_model
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->where('isConfirmed', 1)
            ->count_rows();

        $stock_countings = $this->stock_counting_model
            ->with_dealer(['with' => ['relation' => 'trashed']])
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->where('isConfirmed', 1)
            ->order_by('id', 'desc')
            ->paginate(20, $total_countings_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('stock_counting', 'detail')){
            $authority['detail'] = true;
        }
        if ($this->authentic->authority('stock_counting', 'edit')){
            $authority['edit'] = true;
        }

        $data = [
            'counting_reason' => $this->counting_reason,
            'stock_countings' => $stock_countings,
            'pagination' => $this->stock_counting_model->all_pages,
            'authority' => $authority,
            'title' => '盤點歷史紀錄列表',
            'view' => 'stock_counting/overview',
        ];

        $this->_preload($data);
    }

    public function detail($stock_counting_id)
    {
        $stock_counting = $this->stock_counting_model
            ->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->where('isConfirmed', 1)
            ->get($stock_counting_id);

        if (!$stock_counting_id || !$stock_counting) {
            show_error('查無盤點歷史紀錄');
        }

        $data = [
            'counting_reason' => $this->counting_reason,
            'stock_counting' => $stock_counting,
            'title' => '盤盈虧報表',
            'view' => 'stock_counting/detail',
        ];

        $this->_preload($data);
    }

    public function add()
    {
        $error = '';
        if ($this->input->post()) {
            $counting_reason = $this->input->post('counting_reason');

            $config['upload_path'] = FCPATH . 'uploads/';
            $config['allowed_types'] = 'gif|jpg|png|pdf';
            $config['max_size'] = 10000000; //10M
            $config['file_ext_tolower'] = true;
            $config['encrypt_name'] = true;
            $this->load->library('upload', $config);

            if ($_FILES['description_file'] && $_FILES['description_file']['size']) {
                if ($this->upload->do_upload('description_file')) {
                    $upload_data = $this->upload->data();
                    $description_file = '/uploads/' . $upload_data['file_name'];
                } else {
                    $error[] = strip_tags($this->upload->display_errors());
                }
            } else {
                $error[] = '上傳已簽名之盤點表至電腦中指定資料夾';
            }

            if (!$counting_reason || !in_array($counting_reason, array_keys($this->counting_reason))){
                $error[] = '請選擇盤點事由';
            }

            if (!$error) {
                $serialNum = $this->stock_counting_model->getNextSerialNum($counting_reason);
                $stock_counting_id = $this->stock_counting_model->insert([
                    'serialNum' => $serialNum,
                    'countingNum' => $counting_reason.date('Ymd').$serialNum,
                    'counting_reason' => $counting_reason,
                    'description_file' => $description_file,
                    'retailer_id' => $this->dealer['retailer_id'],
                    'dealer_id' => $this->dealer['id'],
                ]);

                redirect(base_url('/stock_counting/edit/' . $stock_counting_id));
            }
        }

        $data = [
            'error' => $error,
            'counting_reason' => $this->counting_reason,
            'title' => '盤盈虧報表新增',
            'view' => 'stock_counting/add',
        ];

        $this->_preload($data);
    }

    public function edit($stock_counting_id)
    {
        $stock_counting = $this->stock_counting_model
            ->where('retailer_id', $this->dealer['retailer_id'])
            ->get($stock_counting_id);

        if (!$stock_counting_id || !$stock_counting) {
            show_error('查無盤點歷史紀錄');
        }

        $this->load->model('product_model');
        $products = $this->product_model->getUnitProductStocks($this->dealer['retailer_id']);

        if (!$products) {
            show_error('查無產品資料');
        }

        $this->load->model('stock_counting_item_model');

        $diff_reasons = [
            '' => '',
            1 => '外展區陳列',
            2 => '其他',
        ];

        if ($this->input->post()) {
            if ($_POST['submit_save']) {
                $items = (array)$this->input->post('items');
                $diff_files = $_FILES['diff_files'];

                $config['upload_path'] = FCPATH . 'uploads/';
                $config['allowed_types'] = 'gif|jpg|png|pdf';
                $config['max_size'] = 10000000; //10M
                $config['file_ext_tolower'] = true;
                $config['encrypt_name'] = true;
                $this->load->library('upload', $config);

                $this->load->library('stock_lib');

                foreach ($items as $product_id => $item) {
                    foreach ($item as $k => $stock) {
                        $qty = (int)$stock['qty'];
                        if (!empty($stock['date']) && strtotime($stock['date']) > 0) {
                            $date = date('Y-m-d', strtotime($stock['date']));
                        } else {
                            $date = null;
                        }
                        $diff_reason = empty($stock['diff_reason']) ? 0 : (int)$stock['diff_reason'];

                        $diff_file = null;

                        if (!empty($diff_files['size'][$product_id][$k])) {
                            $_FILES['image']['name'] = $diff_files['name'][$product_id][$k];
                            $_FILES['image']['type'] = $diff_files['type'][$product_id][$k];
                            $_FILES['image']['tmp_name'] = $diff_files['tmp_name'][$product_id][$k];
                            $_FILES['image']['error'] = $diff_files['error'][$product_id][$k];
                            $_FILES['image']['size'] = $diff_files['size'][$product_id][$k];

                            if ($this->upload->do_upload('image')) {
                                $upload_data = $this->upload->data();
                                $diff_file = '/uploads/' . $upload_data['file_name'];
                            }
                        }

                        $diff_reason_text = null;
                        if ($diff_reason) {
                            if ($diff_reason == 3) {
                                if ($stock['diff_reason_text']) {
                                    $diff_reason_text = $stock['diff_reason_text'];
                                }
                            } else {
                                $diff_reason_text = $diff_reasons[$diff_reason];
                            }
                        }

                        $old_stock = 0;
                        if ($products[$product_id]['stocks']){
                            foreach ($products[$product_id]['stocks'] as $s){
                                if ($s['expired_at'] == $date){
                                    $old_stock += $s['stock'];
                                }
                            }
                        }

                        $this->stock_counting_item_model->insert([
                            'stock_counting_id' => $stock_counting_id,
                            'product_id' => $product_id,
                            'old_stock' => $old_stock,
                            'stock' => $qty,
                            'expired_at' => $date,
                            'diff_reason' => $diff_reason_text,
                            'diff_file' => $diff_file,
                        ]);

                        $this->stock_lib->retailer_stock_value($this->dealer['retailer_id'], $product_id, $qty, $date);
                    }
                }

                $this->stock_counting_model->update([
                    'isConfirmed' => 1,
                ], ['id' => $stock_counting_id]);
            } else { //不儲存
                $this->stock_counting_model->delete($stock_counting_id);
            }

            redirect(base_url('/stock_counting/overview'));
        }

        $stock_counting_items = $this->stock_counting_item_model
            ->where('stock_counting_id', $stock_counting_id)
            ->get_all();
        if ($stock_counting_items){
            foreach ($stock_counting_items as $item){
                $this->stock_counting_item_model->delete($item['id']);
            }
        }

        $data = [
            'diff_reason' => $diff_reasons,
            'counting_reason' => $this->counting_reason[$stock_counting['counting_reason']],
            'stock_counting' => $stock_counting,
            'products' => $products,
            'title' => '盤盈虧報表編輯',
            'view' => 'stock_counting/edit',
        ];

        $this->_preload($data);
    }
}

?><file_sep>/application/views/capital/retailer/qualification/overview.php
<div class="container">
    <h1 class="mb-4"><?= $retailer['company'] ?>經銷拓展資格</h1>

    <table class="table table-hover table-bordered table-responsive-sm">
        <tr>
            <th class="text-center">類別</th>
            <th class="text-center">代碼</th>
            <th class="text-center">名稱</th>
            <th class="text-center">折扣</th>
            <th class="text-center">首次進貨門檻</th>
            <th class="text-center">每月進貨門檻</th>
            <th class="text-center">拓展資格</th>
            <th></th>
        </tr>
        <?php
        if ($levels) {
            foreach ($levels as $level) {
                ?>
                <tr>
                    <td class="text-center"><?= $level['type']['type'] ?></td>
                    <td class="text-center"><?= $level['code'] ?></td>
                    <td class="text-center"><?= $level['type']['title'] ?></td>
                    <td class="text-center"><?= $level['discount'] . '%' ?></td>
                    <td class="text-right"><?= $level['firstThreshold'] ? '$'.number_format($level['firstThreshold']) : '' ?></td>
                    <td class="text-right"><?= $level['monthThreshold'] ? '$'.number_format($level['monthThreshold']) : '' ?></td>
                    <td class="text-center"><?= yesno($level['qualification']) ?></td>
                    <td class="text-center">
                        <?php if (!empty($authority['edit'])){ ?>
                        <div class="btn-group" role="group">
                            <a class="btn btn-info btn-sm" href="<?= base_url('/capital_retailer_qualification/edit/' . $retailer['id'] . '/' . $level['id']) ?>">編輯</a>
                        </div>
                        <?php } ?>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="7" class="text-center">查無資料</td>
            </tr>
            <?php
        }
        ?>
    </table>

    <?= $pagination ?>
</div><file_sep>/application/config/setting.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$config['app_title'] = '貨物管理系統 Ver 1.0';


<file_sep>/application/views/stock_counting/add.php
<div class="container">
    <h1 class="mb-4 text-center">盤盈虧報表新增</h1>

    <form method="post" enctype="multipart/form-data">
        <?php if ($error) { ?>
            <div class="alert alert-danger">
                <?= implode('<br>', $error) ?>
            </div>
        <?php } ?>

        <div class="form-group row">
            <label class="col-sm-2 col-form-label font-weight-bold">盤點事由</label>
            <div class="col-sm-10">
                <?php
                echo form_dropdown('counting_reason', $counting_reason, '', 'class="form-control" required');
                ?>
            </div>
        </div>

        <div class="form-group row">
            <label class="col-sm-2 col-form-label font-weight-bold">承辦人</label>
            <div class="col-sm-10">
                <?= $dealer['name'] ?>
            </div>
        </div>

        <div class="form-group row">
            <label class="col-sm-2 form-check-label font-weight-bold">上傳已簽名之盤點表至電腦中指定資料夾</label>
            <div class="col-sm-10">
                <input type="file" class="form-control-file" id="description_file" name="description_file" required />
            </div>
        </div>

        <div class="form-group text-center">
            <input type="submit" class="btn btn-success" value="產生「庫存列表」" />
        </div>
    </form>
</div><file_sep>/application/controllers/Capital_retailer.php
<?php

class Capital_retailer extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('retailer_model');
        $this->load->model('dealer_model');

        $this->session->set_userdata('return_page', base_url('/capital_retailer/overview'));
    }

    public function overview()
    {
        $total_retailers_count = $this->retailer_model
            ->count_rows();

        $retailers = $this->retailer_model
            ->with_role()
            ->with_contact_dealer()
            ->with_level(['with' => ['relation' => 'type']])
            ->order_by('id', 'desc')
            ->paginate(20, $total_retailers_count);

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_retailer', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('capital_retailer', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('capital_retailer', 'cancel')){
            $authority['cancel'] = true;
        }
        if ($this->authentic->authority('capital_dealer', 'overview')){
            $authority['dealer'] = true;
        }
        if ($this->authentic->authority('capital_retailer_qualification', 'overview')){
            $authority['qualification'] = true;
        }
        if ($this->authentic->authority('capital_relationship_shipout', 'overview')){
            $authority['shipout'] = true;
        }
        if ($this->authentic->authority('capital_relationship_shipin', 'overview')){
            $authority['shipin'] = true;
        }
        if ($this->authentic->authority('capital_relationship_invoice', 'overview')){
            $authority['invoice'] = true;
        }
        if ($this->authentic->authority('capital_relationship_invoice_send', 'overview')){
            $authority['invoice_send'] = true;
        }
        if ($this->authentic->authority('capital_relationship_visor', 'overview')){
            $authority['supervisor'] = true;
        }

        $data = [
            'retailers' => $retailers,
            'pagination' => $this->retailer_model->all_pages,
            'authority' => $authority,
            'title' => '單位總覽',
            'view' => 'capital/retailer/overview',
        ];

        $this->load->helper('data_format');

        $this->_preload($data);
    }

    public function add()
    {
        $this->load->model('retailer_role_model');
        $roles = $this->retailer_role_model->getRoleSelect();

        $retailer_selects = $this->retailer_model->getRetailerSelect();
        $dealer_selects = $this->dealer_model->getDealerSelect();

        if ($this->input->post()) {
            $this->form_validation->set_rules('retailer_role_id', '單位類型', 'required|integer|in_list[' . implode(',',array_keys($roles)) . ']');
            $this->form_validation->set_rules('sales_retailer_id', '輔銷單位', 'integer|in_list[' . implode(',',array_keys($retailer_selects)) . ']');
            $this->form_validation->set_rules('sales_dealer_id', '輔銷人', 'integer|in_list[' . implode(',',array_keys($dealer_selects)) . ']');
            $this->form_validation->set_rules('company', '單位名稱', 'required|max_length[20]');
            $this->form_validation->set_rules('invoice_title', '單位抬頭', 'max_length[20]');
            $this->form_validation->set_rules('identity', '統一編號', 'required|max_length[10]');
            $this->form_validation->set_rules('phone', '聯絡電話1', 'required|is_natural|max_length[20]');
            $this->form_validation->set_rules('altPhone', '聯絡電話2', 'is_natural|max_length[20]');
            $this->form_validation->set_rules('address', '聯絡地址', 'required|max_length[100]');
            $this->form_validation->set_rules('firstThreshold', '首次進貨門檻', 'integer|greater_than_equal_to[0]');
            $this->form_validation->set_rules('purchaseThreshold', '每月進貨門檻', 'integer|greater_than_equal_to[0]');
            $this->form_validation->set_rules('hasStock', '管理庫存', 'required|integer|in_list[0,1]');
            $this->form_validation->set_rules('totalStock', '總倉庫存', 'required|integer|in_list[0,1]');
            $this->form_validation->set_rules('isAllowBulk', '散裝進貨資格', 'required|integer|in_list[0,1]');
            $this->form_validation->set_rules('eta_days', '出貨期限', 'integer');
            $this->form_validation->set_rules('bank', '收款銀行', 'max_length[100]');
            $this->form_validation->set_rules('bank_branch', '分行名', 'max_length[100]');
            $this->form_validation->set_rules('bank_account_title', '收款戶名', 'max_length[100]');
            $this->form_validation->set_rules('bank_account', '收款帳戶', 'max_length[100]');

            if ($this->form_validation->run() !== FALSE) {
                $retailer_role_id = $this->input->post('retailer_role_id');

                $this->retailer_model->insert([
                    'sales_retailer_id' => $this->input->post('sales_retailer_id') ? $this->input->post('sales_retailer_id') : null,
                    'sales_dealer_id' => $this->input->post('sales_dealer_id') ? $this->input->post('sales_dealer_id') : null,
                    'retailer_role_id' => $retailer_role_id,
                    'company' => $this->input->post('company'),
                    'invoice_title' => $this->input->post('invoice_title') ? $this->input->post('invoice_title') : null,
                    'bank' => $this->input->post('bank') ? $this->input->post('bank') : null,
                    'bank_branch' => $this->input->post('bank_branch') ? $this->input->post('bank_branch') : null,
                    'bank_account_title' => $this->input->post('bank_account_title') ? $this->input->post('bank_account_title') : null,
                    'bank_account' => $this->input->post('bank_account') ? $this->input->post('bank_account') : null,
                    'identity' => $this->input->post('identity'),
                    'phone' => $this->input->post('phone'),
                    'altPhone' => $this->input->post('altPhone'),
                    'address' => $this->input->post('address'),
                    'firstThreshold' => ($this->input->post('firstThreshold') >= 0) ? $this->input->post('firstThreshold') : null,
                    'purchaseThreshold' => ($this->input->post('purchaseThreshold') >= 0) ? $this->input->post('purchaseThreshold') : null,
                    'hasStock' => $this->input->post('hasStock'),
                    'totalStock' => $this->input->post('totalStock'),
                    'isAllowBulk' => $this->input->post('isAllowBulk'),
                    'eta_days' => $this->input->post('eta_days') ? $this->input->post('eta_days') : null,
                ]);

                redirect(base_url('/capital_retailer/overview/'));
            }
        }

        $this->load->helper('form');

        $data = [
            'roles' => $roles,
            'retailer_selects' => $retailer_selects,
            'dealer_selects' => $dealer_selects,
            'title' => '新增經銷單位',
            'view' => 'capital/retailer/add',
        ];

        $this->_preload($data);
    }

    public function edit($retailer_id)
    {
        $retailer = $this->retailer_model
            ->get($retailer_id);

        if (!$retailer_id || !$retailer) {
            show_error('查無經銷單位資料');
        }

        $retailer_selects = $this->retailer_model->getRetailerSelect();
        $dealer_selects = $this->dealer_model->getDealerSelect();

        $this->load->model('dealer_model');
        $dealers = $this->dealer_model->getDealerSelect($retailer_id);

        if ($this->input->post()) {
            $this->form_validation->set_rules('sales_retailer_id', '輔銷單位', 'integer|in_list[' . implode(',',array_keys($retailer_selects)) . ']');
            $this->form_validation->set_rules('sales_dealer_id', '輔銷人', 'integer|in_list[' . implode(',',array_keys($dealer_selects)) . ']');
            $this->form_validation->set_rules('company', '單位名稱', 'required|max_length[20]');
            $this->form_validation->set_rules('invoice_title', '單位抬頭', 'max_length[20]');
            $this->form_validation->set_rules('identity', '統一編號', 'required|max_length[10]');
            $this->form_validation->set_rules('contact_dealer_id', '單位代表人', 'integer|in_list[' . implode(',',array_keys($dealers)) . ']');
            $this->form_validation->set_rules('phone', '聯絡電話1', 'required|is_natural|max_length[20]');
            $this->form_validation->set_rules('altPhone', '聯絡電話2', 'is_natural|max_length[20]');
            $this->form_validation->set_rules('address', '聯絡地址', 'required|max_length[100]');
            $this->form_validation->set_rules('firstThreshold', '首次進貨門檻', 'integer|greater_than_equal_to[0]');
            $this->form_validation->set_rules('purchaseThreshold', '每月進貨門檻', 'integer|greater_than_equal_to[0]');
            $this->form_validation->set_rules('hasStock', '管理庫存', 'required|integer|in_list[0,1]');
            $this->form_validation->set_rules('totalStock', '總倉庫存', 'required|integer|in_list[0,1]');
            $this->form_validation->set_rules('isAllowBulk', '散裝進貨資格', 'required|integer|in_list[0,1]');
            $this->form_validation->set_rules('eta_days', '出貨期限', 'integer');
            $this->form_validation->set_rules('bank', '收款銀行', 'max_length[100]');
            $this->form_validation->set_rules('bank_branch', '分行名', 'max_length[100]');
            $this->form_validation->set_rules('bank_account_title', '收款戶名', 'max_length[100]');
            $this->form_validation->set_rules('bank_account', '收款帳戶', 'max_length[100]');


            if ($this->form_validation->run() !== FALSE) {
                $this->retailer_model->update([
                    'sales_retailer_id' => $this->input->post('sales_retailer_id') ? $this->input->post('sales_retailer_id') : null,
                    'sales_dealer_id' => $this->input->post('sales_dealer_id') ? $this->input->post('sales_dealer_id') : null,
                    'company' => $this->input->post('company'),
                    'invoice_title' => $this->input->post('invoice_title') ? $this->input->post('invoice_title') : null,
                    'bank' => $this->input->post('bank') ? $this->input->post('bank') : null,
                    'bank_branch' => $this->input->post('bank_branch') ? $this->input->post('bank_branch') : null,
                    'bank_account_title' => $this->input->post('bank_account_title') ? $this->input->post('bank_account_title') : null,
                    'bank_account' => $this->input->post('bank_account') ? $this->input->post('bank_account') : null,
                    'identity' => $this->input->post('identity'),
                    'contact_dealer_id' => $this->input->post('contact_dealer_id') ? $this->input->post('contact_dealer_id') : null,
                    'phone' => $this->input->post('phone'),
                    'altPhone' => $this->input->post('altPhone'),
                    'address' => $this->input->post('address'),
                    'firstThreshold' => ($this->input->post('firstThreshold') >= 0) ? $this->input->post('firstThreshold') : null,
                    'purchaseThreshold' => ($this->input->post('purchaseThreshold') >= 0) ? $this->input->post('purchaseThreshold') : null,
                    'hasStock' => $this->input->post('hasStock'),
                    'totalStock' => $this->input->post('totalStock'),
                    'isAllowBulk' => $this->input->post('isAllowBulk'),
                    'eta_days' => $this->input->post('eta_days') ? $this->input->post('eta_days') : null,
                ], ['id' => $retailer_id]);

                redirect(base_url('/capital_retailer/overview/'));
            }
        }

        $data = [
            'dealers' => $dealers,
            'retailer' => $retailer,
            'retailer_selects' => $retailer_selects,
            'dealer_selects' => $dealer_selects,
            'title' => '編輯經銷單位',
            'view' => 'capital/retailer/edit',
        ];

        $this->_preload($data);
    }

    public function cancel($retailer_id)
    {
        $retailer = $this->retailer_model
            ->get($retailer_id);

        if (!$retailer_id || !$retailer) {
            show_error('查無經銷單位資料');
        }

        if ($retailer['isLocked']){
            show_error('預設經銷單位不能刪除');
        }

        $this->retailer_model->delete($retailer_id);

        redirect(base_url('/capital_retailer/overview/'));
    }
}

?><file_sep>/application/views/consumer/order-return.php
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <h1 class="mb-4">貨到付款退貨作業</h1>

            <form method="post">
                <?php if (validation_errors()) { ?>
                    <div class="alert alert-danger">
                        <?= validation_errors() ?>
                    </div>
                <?php } ?>

                <h4 class="my-4 text-center">已收之退貨內容物</h4>
                <table class="table table-hover table-bordered table-responsive-sm">
                    <tr>
                        <td>項次</td>
                        <td>貨品編號</td>
                        <td>貨品名稱</td>
                        <td>單價</td>
                        <td>訂購數量</td>
                        <td>金額小計</td>
                        <td>折扣</td>
                        <td>折扣價</td>
                    </tr>
                    <?php
                    if ($items) {
                        $i = 1;
                        foreach ($items as $item) {
                            ?>
                            <tr>
                                <td data-th="項次" class="text-center"><?= $i ?></td>
                                <td data-th="貨品編號"><?= $item['product']['p_num'] ?></td>
                                <td data-th="貨品名稱"><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
                                <td data-th="單價" class="text-right">$<?= number_format($item['price']) ?></td>
                                <td data-th="訂購數量" class="text-right"><?= number_format($item['qty']) ?></td>
                                <td data-th="金額小計" class="text-right">$<?= number_format($item['price'] * $item['qty']) ?></td>
                                <td data-th="折扣" class="text-right"><?= $item['discount'] . '%'?></td>
                                <td data-th="折扣價" class="text-right">$<?= number_format($item['subPrice']) ?></td>
                            </tr>
                            <?php
                            $i++;
                        }
                    }
                    ?>
                </table>

                <div class="form-group">
                    <label class="font-weight-bold">已付之退貨運費</label>
                    <input type="number" name="freight" class="form-control text-right"
                           value="<?= set_value('freight', 0) ?>" required/>
                </div>

                <div class="form-group">
                    <label class="font-weight-bold">已付之退貨手續費</label>
                    <input type="number" name="fare" class="form-control text-right"
                           value="<?= set_value('fare', 0) ?>" required/>
                </div>

                <div class="form-group d-flex justify-content-between">
                    <a href="<?=base_url('/consumer/payAtShipped')?>" class="btn btn-secondary">取消</a>
                    <input type="submit" class="btn btn-success" value="退貨完成"/>
                </div>
            </form>
        </div>
    </div>
</div><file_sep>/application/views/supervisor/info.php
<div class="container">
    <h1 class="mb-4"><?= $retailer['company'] ?>經銷單位基本資料</h1>
    <p class="card-text">經銷商類別: <?= $retailer['level_title'] ?></p>
    <p class="card-text">加入經銷商日期: <?= date('Y/m/d', strtotime($retailer['created_at'])) ?></p>
    <p class="card-text">身份證字號/統一編號: <?= $retailer['identity'] ?></p>
    <p class="card-text">聯絡電話1: <?= $retailer['phone'] ?></p>
    <p class="card-text">聯絡電話2: <?= $retailer['altPhone'] ?></p>
    <p class="card-text">送貨地址: <?= $retailer['address'] ?></p>
    <?php if (!empty($retailer['sales_retailer'])) { ?>
        <p class="card-text">輔銷單位: <?= $retailer['sales_retailer']['company'] ?></p>
    <?php } ?>
    <?php if (!empty($retailer['sales_dealer'])) { ?>
        <p class="card-text">輔銷人: <?= $retailer['sales_dealer']['name'] ?></p>
    <?php } ?>
    <?php if (!empty($retailer['contact_dealer'])){
    ?>
        <p class="card-text">主要聯絡人帳號: <?= $retailer['contact_dealer']['account'] ?></p>
        <p class="card-text">主要聯絡人名字: <?= $retailer['contact_dealer']['name'] ?></p>
        <p class="card-text">主要聯絡人性別: <?= $retailer['contact_dealer']['gender'] ? '男' : '女' ?></p>
    <?php
    }
    ?>
</div><file_sep>/application/views/stock_counting/set_print.php
<div class="container">
    <div class="float-right">盤點日期: <?=date('Y/m/d')?></div>
    <h1 class="mb-4"><?= $dealer['company'] ?>庫存列表</h1>

    <form method="get" action="<?=base_url('/stock_counting/process_print')?>">
        <table class="table table-hover table-bordered table-responsive-sm">
            <tr>
                <th class="text-center" style="width: 5%;">項次</th>
                <th class="text-center" style="width: 25%;">貨品編號</th>
                <th class="text-center" style="width: 28%;">貨品名稱</th>
                <th class="text-center" style="width: 8%;">到期日</th>
                <th class="text-center" style="width: 8%;">庫存數量</th>
                <th class="text-center" style="width: 16%;">盤點量</th>
                <th class="text-center">盤差說明</th>
            </tr>
            <?php
            if ($products) {
                $i = 1;
                foreach ($products as $product_id => $product) {
                    $stocks_row = count($product['stocks']);
            ?>
            <tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
                <td class="text-center" rowspan="<?=$stocks_row?>"><?= $i ?></td>
                <td class="text-center" rowspan="<?=$stocks_row?>"><?= $product['p_num'] ?></td>
                <td class="text-center" rowspan="<?=$stocks_row?>"><?= $product['pdName'] ?> <?= $product['intro2'] ?></td>
                <?php
                if (!empty($product['stocks'][0])){
                ?>
                <td><?=$product['stocks'][0]['expired_at']?></td>
                <td class="text-right"><?=$product['stocks'][0]['stock']?></td>
                <?php
                } else {
                ?>
                <td></td>
                <td class="text-right">0</td>
                <?php
                }
                ?>
                <td class="text-right" rowspan="<?=$stocks_row?>"></td>
                <td class="text-right" rowspan="<?=$stocks_row?>"></td>
            </tr>
            <?php
            if ($stocks_row > 1){
                foreach ($product['stocks'] as $k => $s) {
                    if ($k) {
            ?>
            <tr>
                <td><?=$s['expired_at']?></td>
                <td class="text-right"><?=$s['stock']?></td>
            </tr>
            <?php
                    }
                }
            }
            ?>
                <?php
                    $i++;
                }
            }
            ?>

            <tr>
                <td colspan="2">
                    <label>盤點事由:</label>
                    <?php
                    echo form_dropdown('counting_reason', $counting_reason, '', 'class="form-control"');
                    ?>
                </td>
                <td colspan="2">
                    <h3>陪同人：<span class="text-mute">請簽名</span></h3>
                </td>
                <td colspan="2">
                    <h3>盤點人：<span class="text-mute">請簽名</span></h3>
                </td>
            </tr>
        </table>

        <?php if (!empty($authority['print'])){ ?>
        <div class="text-center my-4">
            <button type="submit" class="btn btn-success">列印</button>
        </div>
        <?php } ?>

    </form>
</div><file_sep>/application/migrations/067_update_retailer_allow_bulk.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_retailer_allow_bulk extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_column('olive_retailers', [
            'isAllowBulk' => [
                'type' => 'tinyint',
                'constraint' => 1,
                'unsigned' => TRUE,
                'default' => 0,
                'after' => 'isLocked',
            ],
        ]);
    }

    public function down()
    {
        $this->dbforge->drop_column('olive_retailers', 'isAllowBulk');
    }
}<file_sep>/application/controllers/Capital_product.php
<?php

class Capital_product extends MY_Controller
{
    protected $dealer;

    public function __construct()
    {
        parent::__construct();

        if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
            redirect(base_url('/'));
        }

        $this->load->model('product_model');

        $this->session->set_userdata('return_page', base_url('/capital_product/overview'));
    }

    public function overview()
    {
        $total_products_count = $this->product_model
            ->count_rows();

        $products = $this->product_model
            ->with_product_kind()
            ->with_pao()
            ->where('pKind', [3,6])
            ->where('pEnable', 'Y')
            ->order_by('pKind', 'asc')
            ->order_by('pdId', 'asc')
            ->paginate(20, $total_products_count);

        //進貨商品管理
        $this->load->model('retailer_model');
        $this->load->model('product_permission_model');
        $retailer_selects = $this->retailer_model->getRetailerSelect();
        $_permissions = $this->product_permission_model->get_all();
        $permissions = [];
        if ($_permissions){
            foreach ($_permissions as $k => $p){
                $retailers = [];
                $_retailers = is_null($p['include_retailers']) ? null : explode(',', $p['include_retailers']);
                if ($_retailers){
                    foreach ($_retailers as $retailer_id){
                        $retailers[] = $retailer_selects[$retailer_id];
                    }
                }
                $p['retailers'] = $retailers;
                $permissions[$p['product_id']] = $p;
            }
        }

        //權限設定
        $authority = array();
        if ($this->authentic->authority('capital_product', 'add')){
            $authority['add'] = true;
        }
        if ($this->authentic->authority('capital_product', 'edit')){
            $authority['edit'] = true;
        }
        if ($this->authentic->authority('capital_product', 'cancel')){
            $authority['cancel'] = true;
        }
        if ($this->authentic->authority('capital_product_permission', 'edit')){
            $authority['permission'] = true;
        }
        if ($this->authentic->authority('capital_product_pao', 'overview')){
            $authority['pao'] = true;
        }

        $data = [
            'products' => $products,
            'permissions' => $permissions,
            'pagination' => $this->product_model->all_pages,
            'authority' => $authority,
            'title' => '商品總覽',
            'view' => 'capital/product/overview',
        ];

        $this->_preload($data);
    }

    public function add()
    {
        $this->load->model('product_kind_model');
        $kind_selects = $this->product_kind_model->getKindSelect();

        $this->load->model('pao_model');
        $pao_selects = $this->pao_model->getPaoSelect();

        if ($this->input->post()) {
            $this->form_validation->set_rules('p_num', '貨品編號', 'required|max_length[20]');
            $this->form_validation->set_rules('pdName', '名稱', 'required|max_length[50]');
            $this->form_validation->set_rules('intro2', '外緣尺寸', 'required|max_length[100]');
            $this->form_validation->set_rules('pdCash', '單價', 'required|integer|greater_than_equal_to[0]');
            $this->form_validation->set_rules('pKind', '分類', 'required|integer|in_list[' . implode(',',array_keys($kind_selects)) . ']');
            $this->form_validation->set_rules('boxAmount', '每箱數量', 'required|integer|greater_than_equal_to[1]');
            $this->form_validation->set_rules('pao_id', '有限期限', 'integer|in_list[' . implode(',',array_keys($pao_selects)) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $this->product_model->insert([
                    'p_num' => $this->input->post('p_num'),
                    'pdName' => $this->input->post('pdName'),
                    'intro2' => $this->input->post('intro2'),
                    'pdCash' => $this->input->post('pdCash'),
                    'pKind' => $this->input->post('pKind'),
                    'boxAmount' => $this->input->post('boxAmount'),
                    'pao_id' => $this->input->post('pao_id') ? $this->input->post('pao_id') : null,
                    'pEnable' => 'Y',
                    'pUpdateDate' => date('Y-m-d H:i:s'),
                    'pdCosts' => null, //有採購系統計算了
                    'inStock' => 0, //已經另外存放庫存
                    'sort_order' => 10, //不知道要幹嘛的
                    'pUpdateStId_link' => 1, //不知道要幹嘛的
                ]);

                redirect(base_url('/capital_product/overview/'));
            }
        }

        $this->load->helper('form');

        $data = [
            'kind_selects' => $kind_selects,
            'pao_selects' => $pao_selects,
            'title' => '新增商品',
            'view' => 'capital/product/add',
        ];

        $this->_preload($data);
    }

    public function edit($product_id)
    {
        $product = $this->product_model
            ->get($product_id);

        if (!$product_id || !$product) {
            show_error('查無商品資料');
        }

        $this->load->model('product_kind_model');
        $kind_selects = $this->product_kind_model->getKindSelect();

        $this->load->model('pao_model');
        $pao_selects = $this->pao_model->getPaoSelect();

        if ($this->input->post()) {
            $this->form_validation->set_rules('p_num', '貨品編號', 'required|max_length[20]');
            $this->form_validation->set_rules('pdName', '名稱', 'required|max_length[50]');
            $this->form_validation->set_rules('intro2', '外緣尺寸', 'required|max_length[100]');
            $this->form_validation->set_rules('pdCash', '單價', 'required|integer|greater_than_equal_to[0]');
            $this->form_validation->set_rules('pKind', '分類', 'required|integer|in_list[' . implode(',',array_keys($kind_selects)) . ']');
            $this->form_validation->set_rules('boxAmount', '每箱數量', 'required|integer|greater_than_equal_to[1]');
            $this->form_validation->set_rules('pao_id', '有限期限', 'integer|in_list[' . implode(',',array_keys($pao_selects)) . ']');

            if ($this->form_validation->run() !== FALSE) {
                $this->product_model->update([
                    'p_num' => $this->input->post('p_num'),
                    'pdName' => $this->input->post('pdName'),
                    'intro2' => $this->input->post('intro2'),
                    'pdCash' => $this->input->post('pdCash'),
                    'pKind' => $this->input->post('pKind'),
                    'boxAmount' => $this->input->post('boxAmount'),
                    'pao_id' => $this->input->post('pao_id') ? $this->input->post('pao_id') : null,
                    'pUpdateDate' => date('Y-m-d H:i:s'),
                ], ['pdId' => $product_id]);

                redirect(base_url('/capital_product/overview/'));
            }
        }

        $data = [
            'kind_selects' => $kind_selects,
            'pao_selects' => $pao_selects,
            'product' => $product,
            'title' => '編輯商品',
            'view' => 'capital/product/edit',
        ];

        $this->_preload($data);
    }

    public function cancel($product_id)
    {
        $product = $this->product_model
            ->get($product_id);

        if (!$product_id || !$product) {
            show_error('查無經銷商品資料');
        }

        $this->product_model->update([
            'pEnable' => 'N',
        ], ['pdId' => $product_id]);

        redirect(base_url('/capital_product/overview/'));
    }
}

?><file_sep>/application/views/shipment/allowance_add.php
<div class="container">
    <h1 class="mb-4">新增銷貨折讓</h1>

    <form method="post">
        <?php if (validation_errors()) { ?>
            <div class="alert alert-danger">
                <?= validation_errors() ?>
            </div>
        <?php } ?>

        <div class="form-group">
            <label class="font-weight-bold">折讓金額</label>
            <input type="number" name="price" class="form-control text-right" min="1"
                   value="<?= set_value('price', 0) ?>" required/>
        </div>

        <div class="form-group d-flex justify-content-between">
            <a href="<?= base_url('/purchase/detail/' . $shipment['ship_id']) ?>" class="btn btn-secondary">取消</a>
            <input type="submit" class="btn_submit btn btn-success" value="送出銷貨折讓"/>
        </div>
    </form>
</div>