zm
2021-03-25 09a98d33fb7521caff9e7dd4494981e7e8fcd5a6
导入卡号和密码功能完成,未测试
1 files added
3 files modified
268 ■■■■■ changed files
plugins/exchange/controllers/mall/LibraryController.php 12 ●●●●● patch | view | raw | blame | history
plugins/exchange/forms/mall/CodeEditForm.php 18 ●●●● patch | view | raw | blame | history
plugins/exchange/forms/mall/ImportForm.php 171 ●●●●● patch | view | raw | blame | history
plugins/exchange/views/library/edit.php 67 ●●●●● patch | view | raw | blame | history
plugins/exchange/controllers/mall/LibraryController.php
@@ -96,4 +96,16 @@
            return $this->asJson($form->import());
        }
    }
    // 模板下载和导出数据
    public function actionExport()
    {
        if (\Yii::$app->request->isPost) {
            $form = new ListForm();
            $form->attributes = \Yii::$app->request->post();
            return $this->asJson($form->export());
        }
    }
}
plugins/exchange/forms/mall/CodeEditForm.php
@@ -141,7 +141,11 @@
                    'valid_start_time' => $newItem['key3'],
                    'created_at' => date("Y-m-d H:i:s"),
                    'r_user_id' => 0,
                    'card_no'=> $newItem['key1']
                    'card_no'=> $newItem['key1'],
                    'r_raffled_at'=>'0000-00-00 00:00:00',
                    'r_origin'=>'',
                    'name'=>'',
                    'mobile'=>''
                ];
                $model->validate();
                $dataList[] = $model->attributes;
@@ -150,19 +154,23 @@
            \Yii::$app->db->createCommand()->batchInsert(
                ExchangeCode::tableName(),
                array_keys($model->attributes),
                $data
                $dataList
            )->execute();
            $transaction->commit();
            return $this->success(['msg' => '保存成功', 'data' => [
                'success' => count($data),
                'fail' => count($list) - count($data),
                'success' => count($dataList),
                'fail' => count($list) - count($dataList),
                'url' => $url
            ]]);
        } catch (\Exception $exception) {
            $transaction->rollBack();
            if($exception->getCode() == '23000'){
                return $this->fail(['msg' => '导入的数据中存在重复的卡号和密码,请修改后重新导入。', 'data' => $list]);
            }else{
            return $this->fail(['msg' => $exception->getMessage(), 'data' => $list]);
        }
    }
    }
    public function success($data)
    {
plugins/exchange/forms/mall/ImportForm.php
New file
@@ -0,0 +1,171 @@
<?php
/**
 * Created by PhpStorm.
 * User: 风哀伤
 * Date: 2020/3/14
 * Time: 9:59
 * @copyright: ©2019 浙江禾匠信息科技
 * @link: http://www.zjhejiang.com
 */
namespace app\plugins\exchange\forms\mall;
use app\core\response\ApiCode;
use app\models\Model;
use yii\helpers\Json;
class ImportForm extends Model
{
    public $file;
    public $library_id;
    public function rules()
    {
        return [
            [['library_id'], 'integer'],
            [['file'], 'file', 'extensions' => ['csv', 'excel']]
        ];
    }
    public function import()
    {
        if (!$this->validate()) {
            return $this->getErrorResponse();
        }
        try {
            set_time_limit(0);
            if (empty($_FILES) || !isset($_FILES['file'])) {
                throw new \Exception('请上传csv或excel文件');
            }
            $fileName = $_FILES['file']['name'];
            $tmpName = $_FILES['file']['tmp_name'];
            $path = \Yii::$app->basePath . '/web/temp/';
            if (!is_dir($path)) {
                mkdir($path);
            }
            $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            $file = time() . \Yii::$app->mall->id . '.' . $ext;
            $uploadFile = $path . $file;
            $result = move_uploaded_file($tmpName, $uploadFile);
            if (!$result) {
                throw new \Exception('文件上传失败,请检查目录是否有权限');
            }
            switch ($ext) {
                case 'csv':
                    $data = $this->getCsvData($uploadFile);
                    break;
                case 'xlsx':
                    $data = $this->getExcelData($uploadFile, $ext);
                    break;
                case 'xls':
                    $data = $this->getExcelData($uploadFile, $ext);
                    break;
                default:
                    throw new \Exception('请上传csv或excel文件');
            }
            if (empty($data)) {
                throw new \Exception('上传的数据为空');
            }
            $form = new CodeEditForm();
            $form->attributes = [
                'library_id' => $this->library_id,
                'list' => Json::encode($data, JSON_UNESCAPED_UNICODE)
            ];
            return $form->batch(true);
        } catch (\Exception $exception) {
            return $this->fail(['msg' => $exception->getMessage()]);
        }
    }
    public function getCsvData($file)
    {
        if (!is_file($file)) {
            exit('没有文件');
        }
        $handle = fopen($file, 'r');
        if (!$handle) {
            exit('读取文件失败');
        }
        $count = 0;
        $newList = [];
        while (($data = fgetcsv($handle)) !== false) {
            $count++;
            // 跳过第一行标题
            if ($count <= 1) {
                continue;
            }
            $index = 1;
            $newItem = [];
            foreach ($data as $item) {
                // 下面这行代码可以解决中文字符乱码问题
                $newItem['key' . $index] = iconv('gbk', 'utf-8', $item);
                $index++;
            }
            $newList[] = $newItem;
        }
        fclose($handle);
        return $newList;
    }
    /**
     * @param $uploadFile
     * @param $ext
     * @throws \PHPExcel_Exception
     * @return array
     */
    public function getExcelData($uploadFile, $ext)
    {
        $reader = \PHPExcel_IOFactory::createReader(($ext == 'xls' ? 'Excel5' : 'Excel2007'));
        $excel = $reader->load($uploadFile);
        $sheet = $excel->getActiveSheet();
        $highestRow = $sheet->getHighestRow(); // 总行数
        $highestColumn = $sheet->getHighestColumn();
        $highestColumnCount = \PHPExcel_Cell::columnIndexFromString($highestColumn); // 总列数
        $row = 0;
        $newList = [];
        while ($row < $highestRow) {
            $row++;
            // 跳过第一行标题
            if ($row <= 1) {
                continue;
            }
            $rowValue = [];
            $col = 0;
            $index = 1;
            while ($col < $highestColumnCount) {
                $rowValue['key' . $index] = (string)$sheet->getCellByColumnAndRow($col, $row)->getValue();
                $col++;
                $index++;
            }
            $newList[] = $rowValue;
        }
        return $newList;
    }
    public function success($data)
    {
        $res = $this->handle($data);
        $res['code'] = ApiCode::CODE_SUCCESS;
        return $res;
    }
    public function fail($data)
    {
        $res = $this->handle($data);
        $res['code'] = ApiCode::CODE_ERROR;
        return $res;
    }
    private function handle($data)
    {
        $msg = $data['msg'] ?? '';
        unset($data['msg']);
        return [
            'msg' => $msg,
            'data' => $data
        ];
    }
}
plugins/exchange/views/library/edit.php
@@ -581,9 +581,10 @@
                <div slot="header" style="width: 100%;" flex="main:justify cross:center">
                    <div>兑换码管理</div>
                    <div>
                        <el-button @click="getActivity" size="small" type="primary">生成动态活码</el-button>
                        <!--<el-button @click="getActivity" size="small" type="primary">生成动态活码</el-button>-->
                        <el-button @click="appendDialog=true;num=''" size="small" type="primary">批量生成兑换码</el-button>
                        <el-button type="primary" @click="uploadVisible = true" size="small">批量导入卡号</el-button>
                        <el-button type="primary" @click="exportData" size="small">导出卡密数据</el-button>
                    </div>
                </div>
                <div class="rules use-rules">
@@ -740,6 +741,7 @@
                    <image style="width: 29px;height: 29px;margin-right:5px" src="statics/img/mall/pass.png"></image>
                    <span>成功导入{{updateData.success}}条数据</span>
                </div>
                <!--
                <div flex="cross:center main:center" style="margin-top: 15px;" >
                    <span style="margin-right: 5px;">
                        未导入
@@ -752,6 +754,7 @@
                        </el-button>
                    </div>
                </div>
            -->
            </div>
        </div>
        <div slot="footer" class="dialog-footer" flex="main:center">
@@ -765,7 +768,7 @@
        width="30%">
        <p flex="cross:center">
            <image src="statics/img/plugins/sigh.png" style="margin-right: 10px;width:30px;height: 30px;"></image>
            <span>请导入不大于2M的Excel文件</span>
            <span>请导入不大于1M的CSV文件</span>
        </p>
        <span slot="footer" class="dialog-footer">
             <el-upload
@@ -773,12 +776,48 @@
                 action=""
                 :multiple="false"
                 :http-request="handleFile"
                 accept=".xls,.csv"
                 accept=".csv"
                 :on-change="excelChange"
                 :show-file-list="false">
                <el-button type="primary" >点击导入</el-button>
            </el-upload>
        </span>
    </el-dialog>
    <el-dialog
            flex="cross:center"
            class="export-dialog"
            title="提示"
            :visible.sync="exportDialogVisible"
            width="20%">
        <template>
            <div>
                <div class="el-message-box__content">
                    <div class="el-message-box__status el-icon-warning"></div>
                    <div class="el-message-box__message">
                        <p>{{exportParams.export == 'export' ? '确认导出卡号密码数据' : '确认下载导入文件模板'}}</p>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <form target="_blank" :action="exportParams.action_url" method="post">
                    <div class="modal-body">
                        <input name="_csrf" type="hidden" id="_csrf"
                               value="<?= Yii::$app->request->csrfToken ?>">
                        <input name="s-keyword" :value="codeSearch.keyword" type="hidden">
                        <input name="s-type" :value="codeSearch.type" type="hidden">
                        <input name="s_created_at_s" :value="codeSearch.created_at[0]" type="hidden">
                        <input name="s_created_at_e" :value="codeSearch.created_at[1]" type="hidden">
                        <input name="s-status" :value="codeSearch.status" type="hidden">
                        <input name="export" :value="exportParams.export" type="hidden">
                    </div>
                    <div flex="dir:right" style="margin-top: 20px;">
                        <button type="submit"
                                class="el-button el-button--primary el-button--small">点击下载</button>
                    </div>
                </form>
            </span>
        </template>
    </el-dialog>
    <!-- 选择奖励品 -->
    <el-dialog title="选择奖励品类型" :visible.sync="chooseDialog" width="590px">
@@ -1210,7 +1249,14 @@
                uploadVisible: false,
                updateDialogVisible: false,
                updateData: null,
                sizeM: 0,
                progress: 0,
                file: '',
                exportParams: {
                    action_url: `<?= Yii::$app->urlManager->createUrl('/plugin/exchange/mall/index/export') ?>`,
                    export: 'export'
                },
                exportDialogVisible: false,
                getActivityCode: false,
                codeShow: true,
                qrVisible: false,
@@ -2042,6 +2088,14 @@
                this.file = file.raw;
            },
            
            updateNo() {
                    const elt = document.createElement('a');
                    elt.setAttribute('href', this.updateData.url);
                    elt.setAttribute('download', '未导入数据.csv');
                    elt.style.display = 'none';
                    document.body.appendChild(elt);
                    elt.click();
            },
            async handleFile() {
                let formData = new FormData();
                let size = this.file.size;
@@ -2075,6 +2129,13 @@
                }
            },
        },
        // 导出数据
        exportData() {
            this.exportDialogVisible = true;
            this.exportParams.export = 'export';
        },
        mounted: function () {
            this.getSvip();
            if(getQuery('id') > 0) {