| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377 |
- <?php
- namespace app\controller\api;
- use app\extra\basic\Base;
- use app\middleware\WxMiddleware;
- use app\model\saas\SaasCart;
- use app\model\saas\SaasCombo;
- use app\model\saas\SaasDiscount;
- use app\model\saas\SaasPrice;
- use app\model\saas\SaasPrintClient;
- use app\model\saas\SaasShop;
- use app\model\saas\SaasUser;
- use app\model\saas\SaasUserBuy;
- use LinFly\Annotation\Route\Controller;
- use LinFly\Annotation\Route\Middleware;
- use LinFly\Annotation\Route\Route;
- use Qcloud\Cos\Client;
- use support\Request;
- use support\Response;
- use yzh52521\EasyHttp\Http;
- #[Controller(prefix: "/wx_api/cart"),Middleware(WxMiddleware::class)]
- class Cart extends Base
- {
- protected array $noNeedLogin = [];
- /**
- * 颜色
- * @var array|string[]
- */
- protected array $color = ["1" => "彩色", "2" => "黑白"];
- /**
- * 单双面
- * @var array|string[]
- */
- protected array $duplex = ["1" => "单面", "2" => "双面"];
- /**
- * 打印方向
- * @var array|string[]
- */
- protected array $direction = ["1" => "自适应","2" => "横向", "3" => "竖向"];
- /**
- * 配送方式
- * @var array|string[]
- */
- protected array $package = ["1" => "店内打印", "2" => '远程自取' , "3" => "商家配送"];
- protected array $types = [
- '1_1_1' => ['name' => '彩色-单面', 'amount' => 0, 'quantity' => 0,'discount' => 0],
- '1_2_1' => ['name' => '彩色-双面', 'amount' => 0, 'quantity' => 0,'discount' => 0],
- '2_1_1' => ['name' => '黑白-单面', 'amount' => 0, 'quantity' => 0,'discount' => 0],
- '2_2_1' => ['name' => '黑白-双面', 'amount' => 0, 'quantity' => 0,'discount' => 0],
- ];
- /**
- * 获取打印购物车列表
- * @return Response
- */
- #[Route(path: "list",methods: "get")]
- public function getCartList(Request $request): Response
- {
- try {
- $param = $this->_valid([
- "shop.require" => trans("empty.require"),
- "print.require" => trans("empty.require"),
- "type.default" => 1
- ]);
- if (!is_array($param)) return error($param);
- $cart = (new SaasCart)->where("shop_id",$param['shop'])->order("create_at desc")->select();
- if ($cart->isEmpty()) return success('ok',['cart' => []]);
- $totalAmount = $totalDiscount = 0;
- foreach ($cart as $k=>$v){
- $key = $v['color'] . '_' . $v['duplex'] . '_' . $v['source'];
- if (isset($this->types[$key])) {
- $this->types[$key]['quantity'] += $v['page'];
- $this->types[$key]['amount'] += $v['money'];
- }
- $cart[$k] = $v;
- $cart[$k]['money'] = format_money($v['money'] / 100,2);
- $cart[$k]['name'] = msubstr($v['name'],0,12);
- }
- $printData = (new SaasPrintClient)->where("shop_id",$param['shop'])->where("code",$param['print'])->select();
- if ($printData->isEmpty()) return error('无可用打印机');
- $rule = [];
- foreach ($printData as $key=>$value) {
- $rule[$key]['check'] = 0;
- $nameColor = "";
- if (empty($value['rule'])) return error("尚未配置打印机~");
- foreach ($value['rule']['color'] as $key2=>$val) {
- $rule[$key]['color'][$key2][$val] = $this->color[$val];
- $nameColor .= $this->color[$val];
- }
- foreach ($value['rule']['direction'] as $key2=>$val) {
- $rule[$key]['direction'][$key2][$val] = $this->direction[$val];
- }
- foreach ($value['rule']['duplex'] as $key2=>$val) {
- $rule[$key]['duplex'][$key2][$val] = $this->duplex[$val];
- }
- foreach ($value['rule']['package'] as $key2=>$val) {
- $rule[$key]['package'][$key2][$val] = $this->package[$val];
- }
- foreach ($value['rule']['paper_size'] as $key2=>$val) {
- $rule[$key]['paper_size'][$key2][$val] = $val;
- }
- if ($param['print'] == $value['code']) {
- $rule[$key]['check'] = 1;
- }
- $rule[$key]['name'] = $nameColor."-".$value['name'];
- $rule[$key]['code'] = $value['code'];
- }
- // 计算折扣
- foreach ($this->types as $k=>$v) {
- $discount = (new SaasDiscount)->where("shop_id",$param['shop'])->where("keys",$k)->where("number",'<',$v['quantity'])->findOrEmpty();
- if (!$discount->isEmpty()) {
- $v['discount'] = round($v['amount'] * $discount['rate']);
- $this->types[$k]['discount'] = $v['discount'];
- }
- $totalAmount += $v['amount'];
- $totalDiscount += $v['discount'];
- }
- $totalAmount = format_money($totalAmount / 100,2);
- $totalDiscount = format_money($totalDiscount / 100,2);
- if ($param['type'] <> 1) {
- $shop = (new SaasShop)->where("shop_id",$param['shop'])->field("shop_name,shop_address,user_card,user_card_price")->find();
- $isRecharge = (new SaasUserBuy)->where("shop_id",$param['shop'])->where("uid",$request->user['id'])->where("status",1)->sum("money");;
- $cardPrice = [];
- if ($shop['user_card'] < 3) {
- if ($shop['user_card'] == 2) { // 自定义套餐
- $cardPrice = array_values($shop['user_card_price']);
- } else {
- $cardPrice = (new SaasCombo)->where("type",2)->field("id,name,ROUND(money/100,2) as money,ROUND(old_money/100,2) as old_money,is_first")->where("status",1)->select()->toArray();
- }
- $cardPrice = array_filter($cardPrice, function($item) use ($isRecharge) {
- if ($isRecharge > 0) {
- return $item['is_first'] != '1'; // 注意:这里使用松散比较,因为数据中有字符串'1'
- } else {
- return $item;
- }
- });
- foreach ($cardPrice as $key=>$val) {
- $cardPrice[$key] = $val;
- $cardPrice[$key]['money'] = $val['money'];
- $cardPrice[$key]['old_money'] = $val['old_money'];
- }
- $cardPrice = array_values($cardPrice);
- }
- $card = (new SaasUser)->where("openid",$request->user['openid'])->where("shop_id",$param['shop'])->field("ROUND(balance/100,2) as money")->findOrEmpty();
- if ($card->isEmpty()) {
- $card = null;
- }
- $package = $this->package;
- return success("",compact('rule','totalAmount','totalDiscount','shop','cardPrice','package','card'));
- }
- return success("",compact('cart','rule','totalAmount','totalDiscount'));
- } catch (\Throwable $th) {
- return error($th->getMessage());
- }
- }
- /**
- * 删除购物
- * @param Request $request
- * @return Response
- */
- #[Route(path: "del",methods: "post")]
- public function delCart(Request $request): Response
- {
- try {
- $param = $this->_valid([
- "shop.require" => trans("empty.require"),
- "id.require" => trans("empty.require"),
- "print.require" => trans("empty.require"),
- ],"post");
- if (!is_array($param)) return error($param);
- $cart = (new SaasCart)->where("id",$param['id'])->findOrEmpty();
- if ($cart->isEmpty()) return error("操作失败");
- if ($cart['uuid'] <> $request->user['id']) return error("操作失败");
- $state = $cart->delete();
- if (!$state) return error("操作失败");
- return success("操作成功");
- } catch (\Throwable $exception) {
- return error($exception->getMessage());
- }
- }
- /**
- * 更新购物
- * @param Request $request
- * @return Response
- */
- #[Route(path: "update",methods: "post")]
- public function updateCart(Request $request): Response
- {
- try {
- $param = $request->post();
- $cart = (new SaasCart)->where("id",$param['id'])->where("uuid",$request->user['id'])->findOrEmpty();
- if ($cart->isEmpty()) return error('数据格式错误');
- if ($param['end_page'] > $cart['total_page']) return error('打印范围不能大于总页数');
- // 查询默认打印机是否有额外收费规则
- $printData = (new SaasPrintClient)->where("shop_id",$param['shop_id'])->where("code",$param['print'])->findOrEmpty();
- $extraMoney = 0;
- $moneyMode = (new SaasPrice)->where([
- "shop_id" => $param['shop_id'],
- "paper_size" => $param['paper_size'],
- "type" => $param['source'],
- "color" => $param['color'],
- "duplex" => $param['duplex'],
- ])->findOrEmpty();
- if ($moneyMode->isEmpty()) return error("尚未设置收费规则");
- if (!empty($printData['price']) && $printData['is_price'] == 1) {
- $priceRule = isset($printData['price'][$moneyMode['id']]['price']) ? $printData['price'][$moneyMode['id']]['price'] : 0;
- $extraMoney = $priceRule * 100;
- }
- if ($param['duplex'] == 2) {
- $updateData['page'] = ceil(($param['end_page'] - $param['start_page'] + 1) / 2); // 双面
- } else {
- $updateData['page'] = $param['end_page'] - $param['start_page'] + 1;
- }
- $updateData['extra_money'] = $extraMoney;
- $updateData['money'] = ($moneyMode['price']*100 + $extraMoney) * $updateData['page'] * $param['number'];
- $updateData['single_money'] = $moneyMode['price']*100;
- $updateData['single_id'] = $moneyMode['id'];
- $updateData['paper_size'] = $param['paper_size'];
- $updateData['number'] = $param['number'];
- $updateData['duplex'] = $param['duplex'];
- $updateData['direction'] = $param['direction']??1;
- $updateData['color'] = $param['color'];
- $updateData['start_page'] = $param['start_page'];
- $updateData['end_page'] = $param['end_page'];
- $state = $cart->save($updateData);
- if (!$state) return error("数据操作失败");
- return success("更新成功");
- } catch (\Throwable $exception) {
- return error($exception->getMessage());
- }
- }
- /**
- * 预览
- * @return Response
- */
- #[Route(path: "preview",methods: "post")]
- public function wordPreview(): Response
- {
- try {
- return success("",[
- "host" => "https://".sConf("storage.cos_http_domain")."/",
- "query" => "?ci-process=doc-preview&dstType=jpg&imageDpi=120&page="
- ]);
- } catch (\Throwable $th) {
- return error($th->getMessage());
- }
- }
- /**
- * 图片打印
- * @return Response
- */
- #[Route(path: "image",methods: "post")]
- public function uploadMultiImage(): Response
- {
- try {
- return success("");
- } catch (\Throwable $th) {
- return error($th->getMessage());
- }
- }
- /**
- * 文档打印
- * @return Response
- */
- #[Route(path: "word",methods: "post")]
- public function uploadWord(Request $request): Response
- {
- try {
- $param = $this->_valid([
- "shop.require" => trans("empty.require"),
- "word.require" => trans("empty.require"),
- "print.require" => trans("empty.require"),
- "type.default" => 1, // 1打印 2复印
- ],$request->method());
- if (!is_array($param)) return error($param);
- $wordData = json_decode($param["word"], true);
- $printData = (new SaasPrintClient)->where(['shop_id' => $param['shop'],'code' => $param['print']])->findOrEmpty();
- if ($printData->isEmpty()) return error('无可用打印机');
- $paperRule = is_string($printData['rule'])?json_decode($printData['rule'],true):$printData['rule'];
- $paperSize = count($paperRule['paper_size'])==1?$paperRule['paper_size'][0]:'A4';
- $colorSize = count($paperRule['color'])==1?$paperRule['color'][0]:2;
- $moneyMode = (new SaasPrice)->where(['shop_id' => $param['shop'],'paper_size' => $paperSize,'color' => $colorSize,'type' => $param['type']])->findOrEmpty();
- if ($moneyMode->isEmpty()) return error("店铺未设置收费规则");
- $extraMoney = 0;
- // 计算额外收费
- if (!empty($printData['price']) && $printData['is_price'] == 1) {
- $priceRule = isset($printData['price'][$moneyMode['id']]['price']) ? $printData['price'][$moneyMode['id']]['price'] : 0;
- $extraMoney = $priceRule * 100 ;
- }
- $cartData = [];
- foreach ($wordData as $key=>$val) {
- $cartData[$key] = [
- "money" => ($val['total'] * $moneyMode['price'] * 100) + ($extraMoney * $val['total']),
- "extra_money" => $extraMoney,
- "number" => 1,
- "duplex" => 1,
- "color" => $colorSize,
- "page" => $val['total'],
- "total_page" => $val['total'],
- "end_page" => $val['total'],
- "name" => $val['name'],
- "uuid" => $request->user['id'],
- "shop_id" => $param['shop'],
- "paper_size" => $paperSize,
- "extension" => $val['ext'],
- "source" => $param['type'],
- "icon" => "https://inmei-print.oss-cn-guangzhou.aliyuncs.com/extension/{$val['ext']}.png", // 图标
- "single_money" => $moneyMode['price'] * 100,
- "single_id" => $moneyMode['id'],
- "path" => $val['cosKey'],
- "print_id" => $param['print'],
- "print_name" => $printData['name'],
- ];
- }
- if (empty($cartData)) return error('上传失败');
- $state = (new SaasCart)->insertAll($cartData);
- if (!$state) return error("解析文档失败,请重试");
- return success("ok");
- } catch (\Throwable $th) {
- return error($th->getMessage());
- }
- }
- /**
- * 读取页码
- * ?ci-process=doc-preview&page=1&dstType=jpg&imageDpi=120
- * ?ci-process=doc-preview&page=2&sheet=1&excelPaperDirection=0
- */
- #[Route(path: "total",methods: ['post','get'])]
- public function checkTotal(Request $request): Response
- {
- try {
- $param = $this->_valid([
- "cosKey.require" => trans("empty.require"),
- ],$request->method());
- if (!is_array($param)) return error($param);
- $suffix = pathinfo($param['cosKey'], PATHINFO_EXTENSION);
- if (empty($suffix)) return error("empty.data.suffix");
- $cosClient = new Client([
- 'region' => sConf("storage.cos_region"),
- 'schema' => 'https', // 协议头部,默认为 http
- 'credentials' => array(
- 'secretId' => sConf("storage.cos_access_key"),
- 'secretKey' => sConf("storage.cos_secret_key"),
- ),
- "verify" => false
- ]);
- $url = $cosClient->getObjectUrl(sConf("storage.cos_bucket"), $param['cosKey']);
- $params = array(
- 'ci-process' => 'doc-preview',
- 'page' => 1,
- 'dstType' => 'jpg',
- 'imageDpi' => '120',
- );
- $query = http_build_query($params);
- $path = $url.$query;
- $resp = Http::get($path)->headers();
- if (!isset($resp['X-Total-Page'])) return error("文档可能需要密码,请先删除后再确认");
- $page = $resp['X-Total-Page']?$resp['X-Total-Page'][0]:1;
- return success("ok",compact('page'));
- } catch (\Throwable $th) {
- return error($th->getMessage());
- }
- }
- }
|