提示:实战项目功能的实现


文章目录

  • 前言
  • 一、商品数据包是什么?
  • 二、实现步骤
  • 1.Route设置
  • 2.数据包的生成开发
  • 总结



前言

提示:有问题请在评论区留言,谢谢:

最近在做电商平台,刚好要实现商品数据包的生成和下载功能,要示包留数据包的存档,生成一次,可以多次下载。


提示:文章有不明白的可以联系我或留言

一、商品数据包是什么?

先来说说什么是商品数据包,商品数据包的作用,为什么要制作商品数据包,为什么不使用接口获取数据而是要生成数据包的形式。
  • 什么是商品数据包:是指将商品数据写入excel或txt,或将商品图片视频打包成zip的形式,并提供大家下载。
  • 商品数据包的作用:特定格式的商品数据包可以在其他平台直接通过导入数据包的形式上架商品到指定平台,比如:生成淘宝的商品数据包可以通过导入的方式批量上架商品到店铺
  • 为什么要制作商品数据包:数据包可以批量上传商品,可简化上架商品的工作
  • 为什么不用接口,而是生成数据包:主要是因为有的平台不支持接口对接互动数据,只支持数据包的形式上传数据。

二、实现步骤

1.Route设置

代码如下(示例):

//商品数据包的生成
Route::group('store/product', function () {
	Route::get('excel/:id', '/excel')->name('merchantStoreProductExcel');
})->prefix('merchant.store.product.Product');

//数据包列表和下载
Route::get('excel/lst', 'merchant.store.Excel/lst')->name('merchantStoreExcelLst');
	Route::get('excel/download/:id', 'merchant.store.Excel/download')->name('merchantStoreExcelDownload');

2.数据包的生成开发

代码如下(示例):

/**
     * @Author:Huidaoli
     * TODO 导出商品数据到excel
     * @Date: 2022-05-10
     * @param $id
     * @return mixed
     */
    public function excel($id)
    {
        if(!$this->repository->merExists($this->request->merId(),$id))
            return app('json')->fail('数据不存在');
        $product = $this->repository->getAdminOneProduct($id,null);
        app()->make(ExcelRepository::class)->create($product->toArray(),$this->request->adminId(),'product',$this->request->merId());
        return app('json')->success('开始导出商品数据');
    }

实现ExcelRepository中的create()功能,getAdminOneProduct()是获取商品详情数据,自己实现即可。

/**
     * TODO
     * @param array $where
     * @param int $admin_id
     * @param string $type
     * @Author:Huidaoli
     * @day 2022-05-10
     */
    public function create(array $where ,int $admin_id, string $type,int $merId)
    {
        $excel = $this->dao->create([
            'mer_id'    => $merId,
            'admin_id'  => $admin_id,
            'type'      => $type
        ]);
      
        $data = ['where' => $where,'type' => $type,'excel_id' => $excel->excel_id];
        Queue::push(SpreadsheetExcelJob::class,$data);
    }

实现队列的功能SpreadsheetExcelJob,可以保证系统的正常运行。

public function fire($job, $data)
    {
        try{
            app()->make(ExcelService::class)->getAll($data);
        }catch (\Exception $e){
            Log::info('导出文件:'.$data['type'].'; error : ' . $e->getMessage());
        }
        $job->delete();
    }

    public function failed($data)
    {
    }

接着来实现ExcelService中的getAll()

public function getAll($data)
    {
        $this->{$data['type']}($data['where'],$data['excel_id']);
    }      Log::info('导出文件:'.$data['type'].'; error : ' . $e->getMessage());
        }
        $job->delete();
    }

    public function failed($data)
    {
    }

上面的商品数据存mysql还是hbase 商品数据库下载_jsonthis->product()方法,来处理商品数据

/**
     * TODO 导出商品
     * @param array $where
     * @param int $id
     * @author Huidaoli
     * @day 2022-05-10
     */
    public function product(array $where,int $id)
    {
        $header = ['商品ID','商品名称','商品简介','关键字','产品条码','品牌','分类id','单位名','销量','售价','市场原价','总库存','主图视频链接','商品封面图片','轮播图','产品资质','直播角本','商品详情','商户名称','分类名称','商品规格'];
        $title = [
            'title' => '商品信息',
            'sheets' => '商品信息',
            'mark' => ['生成时间:' . date('Y-m-d H:i:s',time())],
        ];

        $export = [];
        if(!empty($where)) {
            $i = 1;
            foreach ($where['attrValue'] as &$item) {
                $item['bar_code'] = "\n规格编码:".$item['bar_code'];
                $item['cost'] = "\n规格成本价:".$item['cost'];
                
                if($item['detail']){
                    foreach( $item['detail'] as $key => $val ){
                        $item['detail'] = "\n规格详情:".$key . ":" . $val ;
                    }
                } else{
                    $item['detail'] = "\n规格详情:".$item['detail'];
                }

                $item['extension_one'] = "\n一级佣金:".$item['extension_one'];
                $item['extension_two'] = "\n二级佣金:".$item['extension_two'];
                $item['image'] = "\n规格图片:".$item['image'];
                $item['old_stock'] = "\n老库存:".$item['old_stock'];
                $item['ot_price'] = ($where['ot_price'] == 0.00) ?"\n市场原价:".$where['price']*1.2:"\n市场原价:".$where['ot_price'];
                $item['price'] = "\n售价:".$item['price'];
                $item['product_id'] = "【规格".$i."】>>\n商品ID:".$item['product_id'];
                $item['sales'] = "\n规格销量:".$item['sales'];
                $item['sku'] = "\n规格名:".$item['sku'];
                $item['stock'] = "\n规格库存:".$item['stock'];
                $item['type'] = "\n商品分类:".$item['type'];
                $item['unique'] = "\n规格ID:".$item['unique']."\n\n\n";
                $item['value0'] = "\n规格值:".$item['value0']."\n\n\n";
                $item['volume'] = "\n体积:".$item['volume'];
                $item['weight'] = "\n重量:".$item['weight'];
                
                unset($item['bar_code']);
                unset($item['cost']);
                unset($item['old_stock']);
                unset($item['type']);
                unset($item['volume']);
                unset($item['weight']);
                unset($item['volume']);
                unset($item['weight']);
                
                unset($item['sku']);
                unset($item['value0']);
                
                unset($item['extension_one']);
                unset($item['extension_two']);
                $i++;
            }
            unset($item);
            
            foreach ($where['attrValue'] as $items){
                $items = join(",",$items);
                $sku[] = $items;
            }

            $export[] = [
                $where['product_id'],
                $where['store_name'],
                $where['store_info'],
                $where['keyword'],
                $where['bar_code'],
                $where['brand']['brand_name'],
                $where['cate_id'],
                $where['unit_name'],
                ($where['sales'] == 0) ?10:$where['sales']+30,
                $where['price'],
                ($where['ot_price'] == 0) ?$where['price']*1.2:$where['ot_price'],
                $where['stock'],
                $where['video_link'],
                $where['image'],
                implode(",", $where['slider_image']),
                implode(",", $where['qualification']),
                $where['live_angle'],
                $where['content'],
                $where['merchant']['mer_name'],
                $where['storeCategory']['cate_name'],
                implode(",", $sku)
            ];
        }

        
        $filename = '商品ID:'.$where['product_id'].'_商品数据_'.date('YmdHis');
        $end = [];
        return $this->export($id, 'product', $header, $title, $export,$filename, $end);
    }

接着来实现导出操作

/**
     * TODO 导出操作
     * @param $id
     * @param $path
     * @param $header
     * @param $title
     * @param array $export
     * @param string $filename
     * @param array $end
     * @param string $suffix
     * @author Huidaoli
     * @day 2022-05-10
     */
    public function export($id, $path, $header, $title, $export = [], $filename = '',$end = [],$suffix = 'xlsx')
    {
        try{
            $_path = SpreadsheetExcelService::instance()
                ->createOrActive()
                ->setExcelHeader($header,count($title['mark']) + 2)
                ->setExcelTile($title)
                ->setExcelContent($export)
                ->setExcelEnd($end)
                ->excelSave($filename, $suffix, $path);

            app()->make(ExcelRepository::class)->update($id,[
                'name' => $filename.'.'.$suffix,
                'status' => 1,
                'path' => '/'.$_path
            ]);
        }catch (Exception $exception){
            app()->make(ExcelRepository::class)->update($id,[
                'name' => $filename.'.'.$suffix,
                'status' => 2,
                'message' => $exception->getMessage()
            ]);
        }
    }

到这里已经完成了商品数据导出到excel中的操作,excel被保证在服务器中的product/目录下,并将文件名和文件路径入库保存了,下面我们来实现商品数据列表的接口功能。

/**
     * TODO
     * @return mixed
     * @author Huidaoli
     * @day 2022-05-11
     */
    public function lst()
    {
        [$page, $limit] = $this->getPage();
        $where['type'] = $this->request->param('type','');
        $where['mer_id'] = $this->request->merId();
        $where['admin_id'] = $this->request->adminId();
        return app('json')->success($this->repository->getList($where,$page,$limit));
    }

实现getList()的功能

/**
     * TODO
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     * @author Huidaoli
     * @day 2022-05-11
     */
    public function getList(array $where,int $page, int $limit)
    {
        $mer_make = app()->make(MerchantAdminRepository::class);
        $sys_make = app()->make(AdminRepository::class);
        $query = $this->dao->search($where);
        $count = $query->count();
        $list = $query->page($page,$limit)->select()
            ->each(function($item) use ($mer_make,$sys_make){
                if($item['mer_id']){
                    $admin = $mer_make->get($item['admin_id']);
                }else{
                    $admin = $sys_make->get($item['admin_id']);
                }
                return $item['admin_id'] = $admin['real_name'];
            });

        return compact('count','list');
    }

下面我们来实现下载数据的接口功能

/**
     * TODO 下载文件
     * @param $id
     * @return \think\response\File
     * @author Huidaoli
     * @day 2022-04-30
     */
    public function download($id)
    {
        try{
            if($id == 'express'){
                $file['name'] = 'express';
                $path = app()->getRootPath().'extend/express.xlsx';
                if(!$file || !file_exists($path)) return app('json')->fail('文件不存在');
                return download($path,$file['name']);
            }

            $file = $this->repository->getWhere(['excel_id' => $id,'mer_id' => $this->request->merId()]);
            $path = app()->getRootPath().'public'.$file['path'];
            if(!$file || !file_exists($path)) return app('json')->fail('文件不存在');

            return download($path,$file['name']);
        }catch (UploadException $e){
            return app('json')->fail('下载失败');
        }
    }

到这里全部功能都实现了,不知道大家有没有看明白,里面不重要的方法在文中未列出,大家可以参考实现自己的功能。


总结

以上就是今天要讲的内容,本文仅仅简单介绍了数据包的生成、下载功能的实现,下期给大家来讲下怎么压缩文件,并提供下载压缩文件的方法,谢谢大家的支持,下期见。