CRMEB单商户,增加桌码小程序码

当前版本CRMEB-BZ v5.4.0(20240708)

数据库变更

桌码小程序码

php think migrate:create CreateTableQrcode

public function change()
{
    $table = $this->table('table_qrcode', ['comment' => '桌码二维码', 'signed' => false]);
    $table->addColumn(Column::integer('store_id')->setComment('门店ID')->setSigned(false)->setDefault(0))
        ->addColumn(Column::string('title')->setComment('桌号'))
        ->addColumn(Column::string('qrcode')->setComment('二维码')->setDefault(''))
        ->addColumn(Column::string('remarks')->setComment('备注')->setDefault(''))
        ->addColumn(Column::tinyInteger('enabled')->setComment('启用')->setSigned(false)->setDefault(1))
        ->addColumn(Column::dateTime('create_time')->setComment('创建时间')->setNull(true)->setDefault('CURRENT_TIMESTAMP'))
        ->addColumn(Column::dateTime('update_time')->setComment('更新时间')->setNull(true)->setDefault('CURRENT_TIMESTAMP'))
        ->addIndex('store_id')
        ->addIndex('enabled')
        ->addIndex(['store_id', 'title'], ['unique' => true])
        ->create();
}

订单表桌码小程序码

php think migrate:create UpdateStoreOrderTableQrcode

public function change()
{
    $this->table('store_order')
        ->addColumn(Column::integer('table_qrcode_id')->setComment('桌码ID')->setSigned(false)->setDefault(0))
        ->addColumn(Column::string('table_qrcode_title')->setComment('桌码名称')->setNull(true)->setDefault(''))
        ->update();
}

代码变更

1. 路由变更

app/adminapi/route/setting.php 的路由分组内,增加

/**
 * 桌码(小程序码)
 */
Route::group(function () {
    Route::get('table_qrcode/index', 'TableQrcode/index')->option(['real_name' => '桌码列表']);
    Route::post('table_qrcode/save', 'TableQrcode/save')->option(['real_name' => '保存桌码']);
    Route::delete('table_qrcode/delete/:id', 'TableQrcode/delete')->option(['real_name' => '删除桌码']);
});

app/api/route/v1.php 的路由分组内,增加

/**
 * 桌码
 */
Route::group(function () {
    Route::get('table_qrcode/get/:id', function (Request $request, $id) {
        $id = TableQrcodeServices::parseTableQrcodeScene($id);

        if (empty($id)) {
            return response_json()->fail('桌码数据为空');
        }
        $model = EbTableQrcode::findOrEmpty($id);
        if ($model->isEmpty()) {
            return response_json()->fail('桌码数据为空');
        }

        return response_json()->success($model->toArray());
    })->option(['real_name' => '获取桌码']);
});

2. 控制器变更

新增控制器 app/adminapi/controller/TableQrcode.php

<?php
declare (strict_types=1);

namespace app\adminapi\controller;

use app\Request;
use app\services\TableQrcodeServices;
use ReflectionException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\App;
use think\Response;
use Throwable;

/**
 * 桌码二维码
 */
class TableQrcode extends AuthController
{
    /**
     * @var TableQrcodeServices
     */
    protected $services;

    /**
     * Article constructor.
     * @param App $app
     * @param TableQrcodeServices $service
     */
    public function __construct(App $app, TableQrcodeServices $service)
    {
        parent::__construct($app);
        $this->services = $service;
    }

    /**
     * 列表
     * @return Response
     * @throws ReflectionException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): Response
    {
        $where = $this->request->getMore([
            //['title', ''],
            ['enabled', null],
        ]);
        $where = array_filter($where, function ($value) {
            return $value !== null;
        });
        $data = $this->services->getList($where);
        return response_json()->success($data);
    }

    /**
     * 保存资源
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        $id = $request->post('id');
        $data = $request->postMore([
            ['store_id', 0],
            ['title', ''],
            ['remarks', ''],
            ['enabled', 1],
        ]);

        try {
            $model = $this->services->save($data, $id ? (int)$id : 0);
            return response_json()->success($model->toArray());
        } catch (Throwable $throwable) {
            return response_json()->fail($throwable->getMessage());
        }
    }

    /**
     * 删除资源
     * @param int|string $id
     * @return Response
     */
    public function delete($id): Response
    {
        if (empty($id)) {
            return response_json()->fail('主键必填');
        }
        $this->services->getDao()->destroy((int)$id);
        return response_json()->success();
    }
}

编辑 \app\api\controller\v1\order\StoreOrderController::create 方法

新增创建订单的参数,传递给变量 $table_qrcode_id

// 桌码ID
['table_qrcode_id', 0],

$table_qrcode_id = TableQrcodeServices::parseTableQrcodeScene($table_qrcode_id);

3. 服务层变更

新增服务类 app/services/TableQrcodeServices.php

<?php

namespace app\services;

use app\dao\TableQrcodeDao;
use app\model\EbTableQrcode;
use app\model\system\attachment\SystemAttachmentCategory;
use app\services\other\UploadService;
use app\services\system\attachment\SystemAttachmentServices;
use crmeb\exceptions\AdminException;
use crmeb\services\app\MiniProgramService;
use InvalidArgumentException;
use OSS\Core\OssException;
use ReflectionException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 桌码服务层
 */
class TableQrcodeServices extends BaseServices
{
    /**
     * 前缀
     */
    public const TABLE_QRCODE_PREFIX = 'table_qrcode_';

    /**
     * 构造函数
     * @param TableQrcodeDao $dao
     */
    public function __construct(TableQrcodeDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @return TableQrcodeDao
     */
    public function getDao(): TableQrcodeDao
    {
        return $this->dao;
    }

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     * @throws ReflectionException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getList(array $where, int $page = 0, int $limit = 0): array
    {
        if (!$page && !$limit) {
            [$page, $limit] = $this->getPageValue();
        }
        $list = $this->dao->getList($where, $page, $limit);
        $count = $this->dao->count($where);
        return compact('list', 'count');
    }

    /**
     * 保存(新增或编辑)
     * @param array $data
     * @param int $id
     * @return EbTableQrcode
     * @throws DataNotFoundException
     * @throws DbException
     * @throws OssException
     */
    public function save(array $data, int $id = 0): EbTableQrcode
    {
        // 是否生成小程序码
        $generate = true;
        if ($id) {
            $title = $data['title'] ?? '';
            /** @var EbTableQrcode $model */
            $model = EbTableQrcode::findOrEmpty($id);
            if (!$model) {
                throw new DataNotFoundException('数据不存在');
            }

            $generate = $model->title !== $title;
            foreach ($data as $key => $value) {
                $model->$key = $value;
            }
            $model->save();
        } else {
            $model = EbTableQrcode::create($data);
        }

        if ($generate) {
            $scene = self::TABLE_QRCODE_PREFIX . $model->id;
            $filename = $scene . '.jpg';
            $mini_program = MiniProgramService::miniprogram();
            $qrcode = $mini_program->qrcode;
            $resCode = $qrcode->appCodeUnlimit($scene, '', 280);
            if (!$resCode) {
                throw new AdminException(410167);
            }

            $uploadType = 1;
            $upload = UploadService::init($uploadType);
            $uploadRes = $upload->to('routine/table_qrcode')->validate()->setAuthThumb(false)->stream($resCode, $filename);
            if ($uploadRes === false) {
                throw new AdminException($upload->getError());
            }

            /** @var SystemAttachmentCategory $systemAttachmentCategory */
            $systemAttachmentCategory = SystemAttachmentCategory::where('name', '=', '桌码小程序码')->findOrEmpty();
            if ($systemAttachmentCategory->isEmpty()) {
                $systemAttachmentCategory = new SystemAttachmentCategory();
                $systemAttachmentCategory->pid = 0;
                $systemAttachmentCategory->setAttr('name', '桌码小程序码');
                $systemAttachmentCategory->save();
            }

            $imageInfo = $upload->getUploadInfo();
            $imageInfo['image_type'] = $uploadType;
            /** @var SystemAttachmentServices $systemAttachment */
            $systemAttachment = app()->make(SystemAttachmentServices::class);
            $systemAttachment->attachmentAdd($imageInfo['name'], $imageInfo['size'], $imageInfo['type'], $imageInfo['dir'], $imageInfo['thumb_path'], $systemAttachmentCategory->id, $imageInfo['image_type'], $imageInfo['time'], 1);
            $model->qrcode = $imageInfo['dir'];
            $model->save();
        }

        return $model;
    }

    /**
     * 解析桌码的小程序码,提取桌码表主键
     * @param string|null $value
     * @return int|null
     */
    public static function parseTableQrcodeScene(string $value = null): int
    {
        if (0 === strpos($value, TableQrcodeServices::TABLE_QRCODE_PREFIX)) {
            $id = substr($value, strlen(TableQrcodeServices::TABLE_QRCODE_PREFIX));
        } else {
            $id = $value;
        }

        if (ctype_digit($id)) {
            return (int)$id;
        }

        throw new InvalidArgumentException('桌码场景值解析失败');
    }
}

变更 \app\services\order\StoreOrderCreateServices::createOrder 方法

新增一个参数 $table_qrcode_id

在定义 $orderInfo 变量前,增加代码

// 桌码 david 2024年11月22日 10:34:58
$table_qrcode = null;
if ($table_qrcode_id) {
    /** @var EbTableQrcode $table_qrcode */
    $table_qrcode = EbTableQrcode::findOrEmpty($table_qrcode_id);
    if ($table_qrcode->isEmpty()) {
        throw new ApiException('桌码无效');
    }
    if (!$table_qrcode->enabled) {
        throw new ApiException('桌码未启用');
    }
}

在赋值 $orderInfo 变量时,增加代码

'table_qrcode_id' => $table_qrcode_id,
'table_qrcode_title' => $table_qrcode instanceof EbTableQrcode ? $table_qrcode->title : '',

4. DAO层变更

新增DAO类 app/dao/TableQrcodeDao.php

<?php

namespace app\dao;

use app\model\EbTableQrcode;
use ReflectionException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 桌码DAO层
 */
class TableQrcodeDao extends BaseDao
{
    /**
     * 设置模型
     * @return string
     */
    protected function setModel(): string
    {
        return EbTableQrcode::class;
    }

    /**
     * 列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     * @throws ReflectionException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getList(array $where, int $page, int $limit): array
    {
        return $this->search($where)->page($page, $limit)->order('id desc')->select()->toArray();
    }
}

5. 模型层变更

新增模型类 app/model/EbTableQrcode.php

<?php

namespace app\model;

use think\Model;

/**
 * 桌码二维码
 * @property integer $id (主键)
 * @property integer $store_id 门店ID
 * @property string $title 桌号
 * @property string $qrcode 二维码
 * @property string $remarks 备注
 * @property integer $enabled 启用
 * @property string $create_time 创建时间
 * @property string $update_time 更新时间
 */
class EbTableQrcode extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'eb_table_qrcode';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $pk = 'id';
}
最后修改:2024 年 11 月 22 日 01 : 59 PM
如果觉得我的文章对你有用,请随意赞赏

发表评论