Hướng dẫn lên đơn shopee lên hệ thống

0
154

Code thêm mục lên đơn trên menu trong themes : header.php

<?php if ($this->Owner || $this->Admin) {?>
                                            <li id="products_count_stock">
                                                                    <a class="submenu" href="<?= admin_url('sales/sale_by_shopee_xls'); ?>">
                                                <i class="fa fa-plus-circle"></i>
                                                <span class="text"> Up file shopee</span>
                                                                    </a>
                                            </li>
                                     
                                    <?php } ?>

Trong database :

ALTER TABLE `sma_product_variants` ADD `code_bienthe` VARCHAR(30) NULL COMMENT 'code biến thể sản phẩm ' AFTER `quantity`;

Trong phần controller file Sales.php :

public function sale_by_shopee_xls() {
      $this->load->helper('security');
      $this->form_validation->set_rules('userfile', lang("upload_file"), 'xss_clean');
      $this->form_validation->set_message('is_natural_no_zero', lang("no_zero_required"));

      if (isset($_FILES["userfile"])) {
          $giaovan = $this->input->post('giaonhan');
          $warehouse_id = $this->input->post('warehouse');
          $biller_id = $this->input->post('biller');
          $biller_details = $this->site->getCompanyByID($biller_id);
          $biller = $biller_details->name != '-' ? $biller_details->name : $biller_details->company;
          $sale_status = 'completed';
          $payment_status = 'pending';

          $this->load->library('upload');
          $config['upload_path'] = $this->digital_upload_path;
          $config['max_size'] = $this->allowed_file_size;
          $config['allowed_types'] = 'csv|xls|xlsx';
          $config['overwrite'] = true;
          $this->upload->initialize($config);
          if (!$this->upload->do_upload()) {
              echo $this->upload->display_errors();
              ;
              die;
              $error = $this->upload->display_errors();

              $this->session->set_flashdata('error', $error);
              admin_redirect("products/upfileshopee");
          }
          $phpExcel = new PHPExcel;
          $xlsx = $this->upload->file_name;
          $objPHPExcel = PHPExcel_IOFactory::load($this->digital_upload_path . $xlsx);
          //$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
          $sheet = $objPHPExcel->setActiveSheetIndex(0);
          $Totalrow = $sheet->getHighestRow();
          //Lấy ra tên cột cuối cùng
          $LastColumn = $sheet->getHighestColumn();
          //Chuyển đổi tên cột đó về vị trí thứ, VD: C là 3,D là 4
          $TotalCol = PHPExcel_Cell::columnIndexFromString($LastColumn);
          //Tạo mảng chứa dữ liệu
          $data = [];
          //Tiến hành lặp qua từng ô dữ liệu
          //----Lặp dòng, Vì dòng đầu là tiêu đề cột nên chúng ta sẽ lặp giá trị từ dòng 2
          for ($i = 2; $i <= $Totalrow; $i++) {
              //----Lặp cột
              for ($j = 0; $j < $TotalCol; $j++) {
                  // Tiến hành lấy giá trị của từng ô đổ vào mảng
                  $data[$i - 2][$j] = $sheet->getCellByColumnAndRow($j, $i)->getValue();
                  ;
              }
          }
          $arrResult = $data;
          #xóa file xls;
          unlink($this->digital_upload_path . $xlsx);
          $array_id_donhang = array();
          $array_infocoban_donhang = array();
          //Hiển thị mảng dữ liệu
          
          foreach ($arrResult as $key => $value) {
              if (!in_array($value[0], $array_id_donhang) && $value[5] != '') {

                  $array_id_donhang[] = $value[0];
                  $array_infocoban_donhang[] = $value;
                  //$array_infocoban_donhang[] = array('tongtien'=>$value[27],'id_donhang'=>$value[0],'name'=>$value[47],'phone'=> $value[48],'tinh'=>$value[49],'quan'=>$value[50],'diachi'=>$value[52]);
              }
          }
          
          for ($i = 0; $i < count($array_infocoban_donhang); $i++) {
              $ma_don_hang = $array_infocoban_donhang[$i][0];
              if ($ma_don_hang != '' AND $this->sales_model->getSalebyReference_no($array_infocoban_donhang[$i][0]) != TRUE) {
                  $id_vanchuyen = $array_infocoban_donhang[$i][5];
                  // lấy thông tin khách hàng
                  $sdt_kh =  $array_infocoban_donhang[$i][48];
                  $companies_data = $this->companies_model->getCustomerSuggestions($sdt_kh);
                  
                  // nếu có số điện thoại 
                  if ($companies_data) {
                      $customer_id = $companies_data[0]->id;
                      $customer_name = $array_infocoban_donhang[$i][47];
                  } else {
                      // nếu không có số điện thoại 
                      $tinh_kh= $array_infocoban_donhang[$i][49];
                      if ($tinh_kh == 'TP. Hồ Chí Minh') {
                          $tinh_kh = 'Hồ Chí Minh';
                      }
                      $ten_kh = $array_infocoban_donhang[$i][47];
                      $dia_chi =$array_infocoban_donhang[$i][52];
                      $khu_vuc = $array_infocoban_donhang[$i][50];
                      $data_user_insert = array('group_id' => 3, 'group_name' => 'customer', 'customer_group_id' => 6,
                          'customer_group_name' => 'Khách thường', 'name' => $ten_kh,
                          'address' => $dia_chi, 'city' => $tinh_kh,
                          'state' => $khu_vuc, 'phone' => $array_infocoban_donhang[$i][48],
                          'cf1' => 'shoppee',
                      );
                      $customer_id = $this->companies_model->addCompany($data_user_insert);
                      $customer_name = $array_infocoban_donhang[$i][47];
                  }
                  // lấy thông tin sản phẩm 
                  unset($products);
                  $id_donhang = $array_infocoban_donhang[$i][0];
                  
                  for ($j = 0; $j < count($arrResult); $j++) {
                      if ($id_donhang == $arrResult[$j][0]) {
                          $code_sp = $arrResult[$j][13];
                          $code_bienthe_sp = $arrResult[$j][18];
                          $product_details = $this->sales_model->getProductByCode($code_sp);
                          // nếu có biến thể ;
                          if ($code_bienthe_sp != '')
                          {
                              
                              $item_option = $this->sales_model->getProductVariantByCodebienthe($code_bienthe_sp, $product_details->id);
                          
                          }
                          // nếu không có biến thể 
                          else{
                              $item_option->id = null;
                          }
                          
                              
                              $item_id = $product_details->id;
                              $item_type = $product_details->type;
                              $item_code = $product_details->code;
                              $item_name = $product_details->name;
                              //echo $arrResult[$j][24];
                              //  cột giá ưu đãi
                              $item_net_price = $this->sma->formatDecimal($arrResult[$j][24]);
                              //echo $arrResult[$j][25];
                              $item_quantity = (int) $arrResult[$j][25];

                              $unit = $this->site->getUnitByID($product_details->unit);
                              $subtotal = $item_quantity * $item_net_price;
                              $product = array(
                                  'product_id' => $product_details->id,
                                  'product_code' => $item_code,
                                  'product_name' => $item_name,
                                  'product_type' => $item_type,
                                  'option_id' => $item_option->id,
                                  'net_unit_price' => $item_net_price,
                                  'unit_price' => $item_net_price,
                                  'quantity' => (int) $item_quantity,
                                  'product_unit_id' => $product_details->unit,
                                  'product_unit_code' => $unit->code,
                                  'unit_quantity' => $item_quantity,
                                  'subtotal' => $subtotal,
                                  'warehouse_id' => $warehouse_id,
                                  'unit_price' => $item_net_price,
                                  'real_unit_price' => $item_net_price,
                              );
                              $products[] = $product;	
                      }
                  }
                  $total = $array_infocoban_donhang[$i][27];
                  // số tiền giảm đơn hàng là số tiền phí dịch vụ cho shopee
                  $order_discount = $array_infocoban_donhang[$i][43];
                  // shipping sẽ là phí giao dịch 
                  $shipping = $array_infocoban_donhang[$i][44];

                 
                 
                  $total_discount = $this->sma->formatDecimal(($order_discount + $product_discount), 2);
                  $grand_total = $this->sma->formatDecimal(($total - $order_discount - $shipping), 2);
                  $data = array('date' => $date,
                      'reference_no' => $id_donhang,
                      'customer_id' => $customer_id,
                      'customer' => $customer_name,
                      'biller_id' => $biller_id,
                      'biller' => $biller,
                      'warehouse_id' => $warehouse_id,
                      'total' => $total,
                      
                      'total_discount' => $total_discount,
                      'order_discount' => $order_discount,
                      'product_discount' => $product_discount,
                      'shipping' => $this->sma->formatDecimal($shipping),
                      'grand_total' => $grand_total,
                      'total_items' => $total_items,
                      'sale_status' => $sale_status,
                      'payment_status' => $payment_status,
                      'payment_term' => $payment_term,
                      'due_date' => $due_date,
                      'paid' => 0,
                      'id_vanchuyen' => $id_vanchuyen,
                      'note' => $array_infocoban_donhang[$i][4],
                      'source' => 'shoppee',
                      'created_by' => $this->session->userdata('user_id'),
                  );
                  if ($this->Settings->indian_gst) {
                      $data['cgst'] = $total_cgst;
                      $data['sgst'] = $total_sgst;
                      $data['igst'] = $total_igst;
                  }

                  if ($payment_status == 'paid') {

                      $payment = array(
                          'date' => $date,
                          'reference_no' => $this->site->getReference('pay'),
                          'amount' => $grand_total,
                          'paid_by' => 'cash',
                          'cheque_no' => '',
                          'cc_no' => '',
                          'cc_holder' => '',
                          'cc_month' => '',
                          'cc_year' => '',
                          'cc_type' => '',
                          'created_by' => $this->session->userdata('user_id'),
                          'note' => lang('auto_added_for_sale_by_csv') . ' (' . lang('sale_reference_no') . ' ' . $reference . ')',
                          'type' => 'received',
                      );
                  } else {
                      $payment = array();
                  }
                  
                  $sale_id = $this->sales_model->addSale($data, $products, $payment,$customer_id);
                  
                  
                  
                  if ($sale_id < 1) {
                      echo $sale_id;
                      var_dump($data);
                      die;
                  }
                  $dlDetails = array(
                      'date' => $date,
                      'sale_id' => $sale_id,
                      'do_reference_no' => $id_vanchuyen,
                      //'do_reference_no' =>$id_vanchuyen,
                      'sale_reference_no' => $id_donhang,
                      'customer' => $customer_name,
                      'address' => $array_infocoban_donhang[$i][52] . '<br/> Điện thoại : ' . $array_infocoban_donhang[$i][48],
                      // chỉnh sửa nếu bận sau thuê người 
                      'status' => $giaovan,
                      'delivered_by' => 'GHTK',
                      'received_by' => '',
                      'note' => $array_infocoban_donhang[$i][4],
                      'created_by' => $this->session->userdata('user_id'),
                  );
                  $id_deli = $this->sales_model->addDelivery($dlDetails);
                 
                 
                 
                 
                 
              }
          }
      } 
      if ($this->form_validation->run() == true) {
          $this->session->set_userdata('remove_slls', 1);
          $this->session->set_flashdata('message', 'Tổng số đơn hàng thêm vào là ' . count($array_id_donhang) . '.Bạn kiểm tra lại nhé');
          admin_redirect("sales");
          
      } else {
          $data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
          $this->data['warehouses'] = $this->site->getAllWarehouses();
          $this->data['tax_rates'] = $this->site->getAllTaxRates();
          $this->data['billers'] = $this->site->getAllCompanies('biller');
          $this->data['slnumber'] = $this->site->getReference('so');

          $bc = array(array('link' => base_url(), 'page' => lang('home')), array('link' => admin_url('sales'), 'page' => lang('sales')), array('link' => '#', 'page' => lang('Thêm file xls từ shopee ')));
          $meta = array('page_title' => lang('add_sale_by_csv'), 'bc' => $bc);
          $this->page_construct('sales/sale_by_shopee_xls', $meta, $this->data);
      }
  }

Ở phần model Sales viết thêm hàm getProductVariantByCodebienthe

public function getProductVariantByCodebienthe($code_bienthe_sp, $product_id) {
            $q = $this->db->get_where('product_variants', array('code_bienthe' => $code_bienthe_sp, 'product_id' => $product_id), 1);
            if ($q->num_rows() > 0) {
                return $q->row();
            }
            return FALSE;
        }

Còn ở compani_model chỉnh sửa function getCustomerSuggestions 1 chút do đầu số 84 ở bên shopee :

public function addCompany($data = array())
    {
        $str = substr($data ["phone"], 0, 2);
        if ($str == '84')
            {
                $data ["phone"] = 'hien123'.$data ["phone"];
                $data ["phone"] = str_replace('hien12384', '0', $data ["phone"]);
            }
        if ($this->db->insert('companies', $data)) {
            $cid = $this->db->insert_id();
            return $cid;
        }
        return false;
    }

Còn ở file views : sale_by_shopee_xls.php

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php

header('Content-Type: text/html; charset=UTF-8');

?>
<script type="text/javascript">
    var count = 1, an = 1, product_variant = 0, DT = <?= $Settings->default_tax_rate ?>,
        product_tax = 0, invoice_tax = 0, total_discount = 0, total = 0,
        tax_rates = <?php echo json_encode($tax_rates); ?>;
    //var audio_success = new Audio('<?=$assets?>sounds/sound2.mp3');
    //var audio_error = new Audio('<?=$assets?>sounds/sound3.mp3');
    $(document).ready(function () {
        
        <?php if ($Owner || $Admin) { ?>
        if (!localStorage.getItem('sldate')) {
            $("#sldate").datetimepicker({
                format: site.dateFormats.js_ldate,
                fontAwesome: true,
                language: 'sma',
                weekStart: 1,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                forceParse: 0
            }).datetimepicker('update', new Date());
        }
        $(document).on('change', '#sldate', function (e) {
            localStorage.setItem('sldate', $(this).val());
        });
        if (sldate = localStorage.getItem('sldate')) {
            $('#sldate').val(sldate);
        }
        $(document).on('change', '#slbiller', function (e) {
            localStorage.setItem('slbiller', $(this).val());
        });
        if (slbiller = localStorage.getItem('slbiller')) {
            $('#slbiller').val(slbiller);
        }
        <?php } ?>
        if (!localStorage.getItem('slref')) {
            localStorage.setItem('slref', '<?=$slnumber?>');
        }

    });
</script>


<div class="box">
    <div class="box-header">
        <h2 class="blue"><i class="fa-fw fa fa-plus"></i><?= lang('add_sale'); ?></h2>
    </div>
    <div class="box-content">
        <div class="row">
            <div class="col-lg-12">

                <p class="introtext"><?php echo lang('enter_info'); ?></p>
                <?php
                $attrib = array('data-toggle' => 'validator', 'role' => 'form');
                echo admin_form_open_multipart("sales/sale_by_shopee_xls", $attrib);

                ?>
                <div class="row">
                    <div class="col-lg-12">
                        <?php if ($Owner || $Admin) { ?>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <?= lang("date", "sldate"); ?>
                                    <?php echo form_input('date', (isset($_POST['date']) ? $_POST['date'] : ""), 'class="form-control input-tip datetime" id="sldate" required="required"'); ?>
                                </div>
                            </div>
                        <?php } ?>
                        
                        <?php if (!$Settings->restrict_user || $Owner || $Admin) { ?>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <?= lang("biller", "slbiller"); ?>
                                    <?php
                                    $bl[""] = "";
                                    foreach ($billers as $biller) {
                                        $bl[$biller->id] = $biller->company != '-' ? $biller->company : $biller->name;
                                    }
                                    echo form_dropdown('biller', $bl, (isset($_POST['biller']) ? $_POST['biller'] : $Settings->default_biller), 'id="slbiller" data-placeholder="' . $this->lang->line("select") . ' ' . $this->lang->line("biller") . '" required="required" class="form-control input-tip select" style="width:100%;"');
                                    ?>
                                </div>
                            </div>
                        <?php } else {
                            $biller_input = array(
                                'type' => 'hidden',
                                'name' => 'biller',
                                'id' => 'slbiller',
                                'value' => $this->session->userdata('biller_id'),
                            );
                            
                            echo form_input($biller_input);
                        } ?>


                                    <?php if (!$Settings->restrict_user || $Owner || $Admin) { ?>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <?= lang("warehouse", "slwarehouse"); ?>
                                                <?php
                                                $wh[''] = '';
                                                foreach ($warehouses as $warehouse) {
                                                    $wh[$warehouse->id] = $warehouse->name;
                                                }
                                                echo form_dropdown('warehouse', $wh, (isset($_POST['warehouse']) ? $_POST['warehouse'] : $Settings->default_warehouse), 'id="slwarehouse" class="form-control input-tip select" data-placeholder="' . $this->lang->line("select") . ' ' . $this->lang->line("warehouse") . '" required="required" style="width:100%;" ');
                                                ?>
                                            </div>
                                        </div>
                                    <?php } else {
                                        $warehouse_input = array(
                                            'type' => 'hidden',
                                            'name' => 'warehouse',
                                            'id' => 'slwarehouse',
                                            'value' => $this->session->userdata('warehouse_id'),
                                        );

                                        echo form_input($warehouse_input);
                                    } ?>
                        
                        <div class="col-md-6">
                            <div class="form-group">
                                <h2>File shopee</h2>
                                <input type="file" data-browse-label="<?= lang('browse'); ?>" name="userfile" required="required"
                                       data-show-upload="false" data-show-preview="false" class="form-control file">
                            </div>
                        </div>
                        
                        <div class="clearfix"></div>

                        <?php if ($Settings->tax2) { ?>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <?= lang("order_tax", "sltax2"); ?>
                                    <?php
                                    $tr[""] = "";
                                    foreach ($tax_rates as $tax) {
                                        $tr[$tax->id] = $tax->name;
                                    }
                                    echo form_dropdown('order_tax', $tr, (isset($_POST['order_tax']) ? $_POST['order_tax'] : $Settings->default_tax_rate2), 'id="sltax2" data-placeholder="' . $this->lang->line("select") . ' ' . $this->lang->line("order_tax") . '" class="form-control input-tip select" style="width:100%;"');
                                    ?>
                                </div>
                            </div>
                        <?php } ?>

                              
                        <div class="col-md-6">            
                                <div class="form-group">
                                   <label class="control-label" for="customer_group">Trạng thái giao vận</label>
                                                            <select class="form-control m-bot15 select2" name="giaonhan" >
                                                                   
                                                                   <option value="packing">Đóng hàng</option>
                                                                   <option value="delivering">Đang giao</option>
                                                                   <option value="delivered">Đã nhận</option>
                                             </select>
                                </div>        
                        </div>
                       
                        <div class="clearfix"></div>

                        <div id="payments" style="display: none;">
                            <div class="col-md-12">
                                <div class="well well-sm well_1">
                                    <div class="col-md-12">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <?= lang("payment_reference_no", "payment_reference_no"); ?>
                                                    <?= form_input('payment_reference_no', (isset($_POST['payment_reference_no']) ? $_POST['payment_reference_no'] : $payment_ref), 'class="form-control tip" id="payment_reference_no" required="required"'); ?>
                                                </div>
                                            </div>
                                            <div class="col-sm-4">
                                                <div class="payment">
                                                    <div class="form-group ngc">
                                                        <?= lang("amount", "amount_1"); ?>
                                                        <input name="amount-paid" type="text" id="amount_1"
                                                               class="pa form-control kb-pad amount"/>
                                                    </div>
                                                    <div class="form-group gc" style="display: none;">
                                                        <?= lang("gift_card_no", "gift_card_no"); ?>
                                                        <input name="gift_card_no" type="text" id="gift_card_no"
                                                               class="pa form-control kb-pad"/>

                                                        <div id="gc_details"></div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-sm-4">
                                                <div class="form-group">
                                                    <?= lang("paying_by", "paid_by_1"); ?>
                                                    <select name="paid_by" id="paid_by_1" class="form-control paid_by">
                                                        <?= $this->sma->paid_opts(); ?>
                                                    </select>
                                                </div>
                                            </div>

                                        </div>
                                        <div class="clearfix"></div>
                                        <div class="pcc_1" style="display:none;">
                                            <div class="row">
                                                <div class="col-md-4">
                                                    <div class="form-group">
                                                        <input name="pcc_no" type="text" id="pcc_no_1"
                                                               class="form-control" placeholder="<?= lang('cc_no') ?>"/>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group">
                                                        <input name="pcc_holder" type="text" id="pcc_holder_1"
                                                               class="form-control"
                                                               placeholder="<?= lang('cc_holder') ?>"/>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group">
                                                        <select name="pcc_type" id="pcc_type_1"
                                                                class="form-control pcc_type"
                                                                placeholder="<?= lang('card_type') ?>">
                                                            <option value="Visa"><?= lang("Visa"); ?></option>
                                                            <option
                                                                value="MasterCard"><?= lang("MasterCard"); ?></option>
                                                            <option value="Amex"><?= lang("Amex"); ?></option>
                                                            <option value="Discover"><?= lang("Discover"); ?></option>
                                                        </select>
                                                        <!-- <input type="text" id="pcc_type_1" class="form-control" placeholder="<?= lang('card_type') ?>" />-->
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group">
                                                        <input name="pcc_month" type="text" id="pcc_month_1"
                                                               class="form-control" placeholder="<?= lang('month') ?>"/>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group">

                                                        <input name="pcc_year" type="text" id="pcc_year_1"
                                                               class="form-control" placeholder="<?= lang('year') ?>"/>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group">

                                                        <input name="pcc_ccv" type="text" id="pcc_cvv2_1"
                                                               class="form-control" placeholder="<?= lang('cvv2') ?>"/>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="pcheque_1" style="display:none;">
                                            <div class="form-group"><?= lang("cheque_no", "cheque_no_1"); ?>
                                                <input name="cheque_no" type="text" id="cheque_no_1"
                                                       class="form-control cheque_no"/>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <?= lang('payment_note', 'payment_note_1'); ?>
                                            <textarea name="payment_note" id="payment_note_1"
                                                      class="pa form-control kb-text payment_note"></textarea>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                            </div>
                        </div>

                        <input type="hidden" name="total_items" value="" id="total_items" required="required"/>

                        
                        <div class="col-md-12">
                            <div
                                class="fprom-group"><?php echo form_submit('add_sale', $this->lang->line("submit"), 'id="add_sale" class="btn btn-primary" style="padding: 6px 15px; margin:15px 0;"'); ?>
                                <button type="button" class="btn btn-danger" id="reset"><?= lang('reset') ?></div>
                        </div>
                    </div>
                </div>

                <?php echo form_close(); ?>

            </div>

        </div>
    </div>
</div>

<script type="text/javascript">
    
    $(document).ready(function () {
        var $customer = $('#slcustomer');
    $customer.change(function (e) {
        localStorage.setItem('slcustomer', $(this).val());
        //$('#slcustomer_id').val($(this).val());
    });
    if (slcustomer = localStorage.getItem('slcustomer')) {
        $customer.val(slcustomer).select2({
            minimumInputLength: 1,
            data: [],
            initSelection: function (element, callback) {
                $.ajax({
                    type: "get", async: false,
                    url: site.base_url+"customers/getCustomer/" + $(element).val(),
                    dataType: "json",
                    success: function (data) {
                        callback(data[0]);
                    }
                });
            },
            ajax: {
                url: site.base_url + "customers/suggestions",
                dataType: 'json',
                quietMillis: 15,
                data: function (term, page) {
                    return {
                        term: term,
                        limit: 10
                    };
                },
                results: function (data, page) {
                    if (data.results != null) {
                        return {results: data.results};
                    } else {
                        return {results: [{id: '', text: 'No Match Found'}]};
                    }
                }
            }
        });
        if (count > 1) {
            $customer.select2("readonly", true);
            $customer.val(slcustomer);
            $('#slwarehouse').select2("readonly", true);
            //$('#slcustomer_id').val(slcustomer);
        }
    } else {
        nsCustomer();
    }
    
// Order level shipping and discount localStorage 
if (sldiscount = localStorage.getItem('sldiscount')) {
    $('#sldiscount').val(sldiscount);
}
$('#sltax2').change(function (e) {
    localStorage.setItem('sltax2', $(this).val());
});
if (sltax2 = localStorage.getItem('sltax2')) {
    $('#sltax2').select2("val", sltax2);
}
$('#slsale_status').change(function (e) {
    localStorage.setItem('slsale_status', $(this).val());
});
if (slsale_status = localStorage.getItem('slsale_status')) {
    $('#slsale_status').select2("val", slsale_status);
}


var old_payment_term;
$('#slpayment_term').focus(function () {
    old_payment_term = $(this).val();
}).change(function (e) {
    var new_payment_term = $(this).val() ? parseFloat($(this).val()) : 0;
    if (!is_numeric($(this).val())) {
        $(this).val(old_payment_term);
        bootbox.alert('Unexpected value provided!');
        return;
    } else {
        localStorage.setItem('slpayment_term', new_payment_term);
        $('#slpayment_term').val(new_payment_term);
    }
});
if (slpayment_term = localStorage.getItem('slpayment_term')) {
    $('#slpayment_term').val(slpayment_term);
}

var old_shipping;
$('#slshipping').focus(function () {
    old_shipping = $(this).val();
}).change(function () {
    if (!is_numeric($(this).val())) {
        $(this).val(old_shipping);
        bootbox.alert('Unexpected value provided!');
        return;
    } else {
        shipping = $(this).val() ? parseFloat($(this).val()) : '0';
    }
    localStorage.setItem('slshipping', shipping);
    var gtotal = ((total + product_tax + invoice_tax) - total_discount) + shipping;
    $('#gtotal').text(formatMoney(gtotal));
});
if (slshipping = localStorage.getItem('slshipping')) {
    shipping = parseFloat(slshipping);
    $('#slshipping').val(shipping);
} else {
    shipping = 0;
}

$('#slref').change(function (e) {
    localStorage.setItem('slref', $(this).val());
});
if (slref = localStorage.getItem('slref')) {
    $('#slref').val(slref);
}

$('#slwarehouse').change(function (e) {
    localStorage.setItem('slwarehouse', $(this).val());
});
if (slwarehouse = localStorage.getItem('slwarehouse')) {
    $('#slwarehouse').select2("val", slwarehouse);
}

        // prevent default action usln enter
$('body').bind('keypress', function (e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        return false;
    }
});

// Order tax calcuation 
if (site.settings.tax2 != 0) {
    $('#sltax2').change(function () {
        localStorage.setItem('sltax2', $(this).val());
        loadItems();
        return;
    });
}

// Order discount calcuation 
var old_sldiscount;
$('#sldiscount').focus(function () {
    old_sldiscount = $(this).val();
}).change(function () {
    var new_discount = $(this).val() ? $(this).val() : '0';
    if (is_valid_discount(new_discount)) {
        localStorage.removeItem('sldiscount');
        localStorage.setItem('sldiscount', new_discount);
        loadItems();
        return;
    } else {
        $(this).val(old_sldiscount);
        bootbox.alert('Unexpected value provided!');
        return;
    }

});

//$(document).on('change', '#slnote', function (e) {
        // $('#slnote').redactor('destroy');
        // $('#slnote').redactor({
        //     buttons: ['formatting', '|', 'alignleft', 'aligncenter', 'alignright', 'justify', '|', 'bold', 'italic', 'underline', '|', 'unorderedlist', 'orderedlist', '|', 'link', '|', 'html'],
        //     formattingTags: ['p', 'pre', 'h3', 'h4'],
        //     minHeight: 100,
        //     changeCallback: function (e) {
        //         var v = this.get();
        //         localStorage.setItem('slnote', v);
        //     }
        // });
        // if (slnote = localStorage.getItem('slnote')) {
        //     $('#slnote').redactor('set', slnote);
        // }
        // $('#slinnote').redactor('destroy');
        // $('#slinnote').redactor({
        //     buttons: ['formatting', '|', 'alignleft', 'aligncenter', 'alignright', 'justify', '|', 'bold', 'italic', 'underline', '|', 'unorderedlist', 'orderedlist', '|', 'link', '|', 'html'],
        //     formattingTags: ['p', 'pre', 'h3', 'h4'],
        //     minHeight: 100,
        //     changeCallback: function (e) {
        //         var v = this.get();
        //         localStorage.setItem('slinnote', v);
        //     }
        // });
        // if (slinnote = localStorage.getItem('slinnote')) {
        //     $('#slinnote').redactor('set', slinnote);
        // }

    });

function nsCustomer() {
    $('#slcustomer').select2({
        minimumInputLength: 1,
        ajax: {
            url: site.base_url + "customers/suggestions",
            dataType: 'json',
            quietMillis: 15,
            data: function (term, page) {
                return {
                    term: term,
                    limit: 10
                };
            },
            results: function (data, page) {
                if (data.results != null) {
                    return {results: data.results};
                } else {
                    return {results: [{id: '', text: 'No Match Found'}]};
                }
            }
        }
    });
}
</script>

Vậy là xong giờ đến video up file