xg 2 年之前
父節點
當前提交
8d870c744a

+ 45 - 0
application/admin/command/MobileExportCommand.php

@@ -0,0 +1,45 @@
+<?php
+
+namespace app\admin\command;
+
+
+use app\admin\model\Admin;
+use app\admin\model\MobileExportLog;
+use app\common\service\MobileExport;
+use think\console\Command;
+use think\console\Input;
+use think\console\Output;
+use think\Db;
+
+class MobileExportCommand extends Command
+{
+    protected function configure()
+    {
+        $this
+            ->setName('mobile:export');
+    }
+
+    protected function execute(Input $input, Output $output)
+    {
+        if(MobileExportLog::where('status',1)->find()){
+            return;
+        }
+        $export=MobileExportLog::where('status',0)->find();
+        if(!$export){
+            return;
+        }
+        $export['status']=1;
+        $export->save();
+        try {
+            $list=Db::query($export['sql']);
+            $listCount=count($list);
+            self::log("【{$export['id']}】共{$listCount}条数据");
+            MobileExport::export($list,$export);
+        }catch (\Exception $e){
+            Db::rollback();
+            $export['status']=3;
+            $export->save();
+            self::logError($e);
+        }
+    }
+}

+ 11 - 2
application/admin/controller/Mobile.php

@@ -4,6 +4,7 @@ namespace app\admin\controller;
 
 use app\admin\library\Auth;
 use app\admin\model\Admin;
+use app\admin\model\MobileExportLog;
 use app\common\controller\Backend;
 use app\common\library\MobileConstant;
 use app\common\model\MobileInfo;
@@ -21,6 +22,7 @@ use PhpOffice\PhpSpreadsheet\Style\Alignment;
 use PhpOffice\PhpSpreadsheet\Style\Border;
 use PhpOffice\PhpSpreadsheet\Style\Fill;
 use think\App;
+use think\Cache;
 use think\Config;
 use think\Db;
 use think\Exception;
@@ -84,6 +86,10 @@ class Mobile extends Backend
         list($where, $sort, $order, $offset, $limit,$page) = $this->buildindexparams();
 
         if($this->request->get('export')==1 && $this->auth->check('mobile/_mobile_export')){
+            if(MobileExportLog::exists()){
+                die('有未完成导出,请稍后再试');
+            }
+            $export=MobileExportLog::make($this->admin('id'));
             ini_set('memory_limit',-1);
             ini_set('max_execution_time',0);
             $db=Db::name('mobile');
@@ -92,9 +98,12 @@ class Mobile extends Backend
                 ->where($where)
                 ->where('mobile.type',1)
                 ->orderRaw($this->getOrder())
-                ->select();
+                ->buildSql();
             //dd($list);
-            return MobileExport::export($list,$this->admin());
+            $export['sql']=$list;
+            $export->save();
+            die('已添加到导出日志,请稍后查看');
+            //return MobileExport::export($list,$this->admin());
         }
 
         if ($this->request->isAjax()) {

+ 77 - 0
application/admin/controller/MobileExportLog.php

@@ -0,0 +1,77 @@
+<?php
+
+namespace app\admin\controller;
+
+use app\common\controller\Backend;
+
+/**
+ * 
+ *
+ * @icon fa fa-circle-o
+ */
+class MobileExportLog extends Backend
+{
+    
+    /**
+     * MobileExportLog模型对象
+     * @var \app\admin\model\MobileExportLog
+     */
+    protected $model = null;
+
+    public function _initialize()
+    {
+        parent::_initialize();
+        $this->model = new \app\admin\model\MobileExportLog;
+
+    }
+
+    public function import()
+    {
+        parent::import();
+    }
+
+    /**
+     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
+     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
+     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
+     */
+    
+
+    /**
+     * 查看
+     */
+    public function index()
+    {
+        //当前是否为关联查询
+        $this->relationSearch = false;
+        //设置过滤方法
+        $this->request->filter(['strip_tags', 'trim']);
+        if ($this->request->isAjax()) {
+            //如果发送的来源是Selectpage,则转发到Selectpage
+            if ($this->request->request('keyField')) {
+                return $this->selectpage();
+            }
+            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
+
+            $list = $this->model
+                    
+                    ->where($where)
+                    ->order($sort, $order)
+                    ->paginate($limit);
+            $result = array("total" => $list->total(), "rows" => $list->items());
+
+            return json($result);
+        }
+        return $this->view->fetch();
+    }
+
+    public function del($ids = "")
+    {
+        $export=$this->model->find($ids);
+        if($export['status']==0){
+            $this->error('导出中无法删除');
+        }
+        $export->delete();
+        $this->success();
+    }
+}

+ 5 - 0
application/admin/lang/zh-cn/mobile_export_log.php

@@ -0,0 +1,5 @@
+<?php
+
+return [
+
+];

+ 30 - 0
application/admin/model/MobileExportLog.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace app\admin\model;
+
+use think\Model;
+
+
+class MobileExportLog extends Model
+{
+    protected $autoWriteTimestamp=true;
+    protected $updateTime=null;
+    protected $append=['file_url','name'];
+
+    public static function exists(){
+        return self::where('status',0)->find();
+    }
+    public static function make($adminId){
+        return self::create([
+            'admin_id'=>$adminId,
+            //'filename'=>'/uploads/mobile_export/'.session_create_id().'.csv',
+        ]);
+    }
+
+    public function getFileUrlAttr($_,$model){
+        return request()->domain().$model['filename'];
+    }
+    public function getNameAttr($_,$model){
+        return basename($model['filename']);
+    }
+}

+ 23 - 0
application/admin/view/mobile_export_log/index.html

@@ -0,0 +1,23 @@
+<div class="panel panel-default panel-intro">
+    {:build_heading()}
+
+    <div class="panel-body">
+        <div id="myTabContent" class="tab-content">
+            <div class="tab-pane fade active in" id="one">
+                <div class="widget-body no-padding">
+                    <div id="toolbar" class="toolbar">
+                        <a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}" ><i class="fa fa-refresh"></i> </a>
+
+                        
+                    </div>
+                    <table id="table" class="table table-striped table-bordered table-hover table-nowrap"
+                           data-operate-edit="0"
+                           data-operate-del="{:$auth->check('mobile_export_log/del')}" 
+                           width="100%">
+                    </table>
+                </div>
+            </div>
+
+        </div>
+    </div>
+</div>

+ 1 - 0
application/command.php

@@ -21,4 +21,5 @@ return [
     \app\common\command\TestCommand::class,
     \app\common\command\OrderExpiredCommand::class,
     \app\admin\command\MobileImportCommand::class,
+    \app\admin\command\MobileExportCommand::class,
 ];

+ 48 - 0
application/common/model/MobileExportLog.php

@@ -0,0 +1,48 @@
+<?php
+
+namespace app\common\model;
+
+use think\Model;
+
+
+class MobileExportLog extends Model
+{
+
+    
+
+    
+
+    // 表名
+    protected $table = 'mobile_export_log';
+    
+    // 自动写入时间戳字段
+    protected $autoWriteTimestamp = false;
+
+    // 定义时间戳字段名
+    protected $createTime = false;
+    protected $updateTime = false;
+    protected $deleteTime = false;
+
+    // 追加属性
+    protected $append = [
+        'create_time_text'
+    ];
+    
+
+    
+
+
+
+    public function getCreateTimeTextAttr($value, $data)
+    {
+        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
+        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
+    }
+
+    protected function setCreateTimeAttr($value)
+    {
+        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
+    }
+
+
+}

+ 11 - 6
application/common/service/MobileExport.php

@@ -11,7 +11,8 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet;
 use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
 
 class MobileExport{
-    public static function export($list,$admin){
+    public static function export($list,$export){
+        $admin=Admin::get($export['admin_id']);
         $excel=new Spreadsheet();
         $header=[
             [
@@ -212,11 +213,15 @@ class MobileExport{
 
         $sheet->getColumnDimension('A')->setAutoSize(true);
         $xlsx=new Xlsx($excel);
-        header('Content-Type: application/vnd.ms-excel;charset=UTF-8');
-        $xlsx->save('php://output');
-        return response()
-            ->data('')
-            ->contentType('application/vnd.ms-excel');
+        $export['filename']=sprintf('/uploads/mobile_export/%s',session_create_id().'.xlsx');
+        $filePath=ROOT_PATH.'/public'.$export['filename'];
+        $dir=str_replace(basename($filePath),'',$filePath);
+        if(!is_dir($dir)){
+            mkdir($dir,0777,true);
+        }
+        $xlsx->save($filePath);
+        $export['status']=2;
+        $export->save();
     }
 
     protected static function visible($item){

+ 27 - 0
application/common/validate/MobileExportLog.php

@@ -0,0 +1,27 @@
+<?php
+
+namespace app\common\validate;
+
+use think\Validate;
+
+class MobileExportLog extends Validate
+{
+    /**
+     * 验证规则
+     */
+    protected $rule = [
+    ];
+    /**
+     * 提示消息
+     */
+    protected $message = [
+    ];
+    /**
+     * 验证场景
+     */
+    protected $scene = [
+        'add'  => [],
+        'edit' => [],
+    ];
+    
+}

+ 59 - 0
public/assets/js/backend/mobile_export_log.js

@@ -0,0 +1,59 @@
+define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
+
+    var Controller = {
+        index: function () {
+            // 初始化表格参数配置
+            Table.api.init({
+                extend: {
+                    index_url: 'mobile_export_log/index' + location.search,
+                    add_url: 'mobile_export_log/add',
+                    edit_url: 'mobile_export_log/edit',
+                    del_url: 'mobile_export_log/del',
+                    multi_url: 'mobile_export_log/multi',
+                    import_url: 'mobile_export_log/import',
+                    table: 'mobile_export_log',
+                }
+            });
+
+            var table = $("#table");
+
+            // 初始化表格
+            table.bootstrapTable({
+                url: $.fn.bootstrapTable.defaults.extend.index_url,
+                pk: 'id',
+                sortName: 'id',
+                columns: [
+                    [
+                        {checkbox: true},
+                        {field: 'id', title: __('Id')},
+                        {field: 'filename', title: __('文件名'),formatter(filename,$export){
+                            if($export.status==0){
+                                return $export.name
+                            }else{
+                                return `<a target="_blank" href="${$export.file_url}">${$export.name}</a>`
+                            }
+                            }},
+                        {field: 'create_time', title: __('Created_at'),formatter: Table.api.formatter.datetime,operate: 'RANGE',addclass:'datetimerange'},
+                        {field: 'status', title: __('Status'),searchList:{0:'等待导出',1:'导出中',2:'导出完成',3:'导出失败'},formatter: Table.api.formatter.label},
+                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
+                    ]
+                ]
+            });
+
+            // 为表格绑定事件
+            Table.api.bindevent(table);
+        },
+        add: function () {
+            Controller.api.bindevent();
+        },
+        edit: function () {
+            Controller.api.bindevent();
+        },
+        api: {
+            bindevent: function () {
+                Form.api.bindevent($("form[role=form]"));
+            }
+        }
+    };
+    return Controller;
+});

+ 3 - 0
thinkphp/library/think/console/Command.php

@@ -474,4 +474,7 @@ class Command
             'trace'=>$exception->getTrace()
         ]);
     }
+    protected static function log($data){
+        user_log('commands/'.class_basename(get_called_class()),$data);
+    }
 }