From 0f20d938ff032982e7065faeed63b65e62465fbd Mon Sep 17 00:00:00 2001 From: lanzu_qsy <334039090@qq.com> Date: Wed, 22 Jul 2020 14:23:51 +0800 Subject: [PATCH 001/172] =?UTF-8?q?=E6=96=B0=E5=BA=97=E9=93=BA=E4=BF=A1?= =?UTF-8?q?=E6=81=AF=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/FileUpload.php | 55 ++++++++++++++++++++++ app/Controller/IndexController.php | 26 ++++++++++- app/Controller/StoreController.php | 73 ++++++++++++++++++++++++++++++ app/Controller/TestController.php | 23 ++++++++++ composer.json | 4 +- 5 files changed, 179 insertions(+), 2 deletions(-) create mode 100644 app/Controller/FileUpload.php create mode 100644 app/Controller/StoreController.php create mode 100644 app/Controller/TestController.php diff --git a/app/Controller/FileUpload.php b/app/Controller/FileUpload.php new file mode 100644 index 0000000..0f9f63a --- /dev/null +++ b/app/Controller/FileUpload.php @@ -0,0 +1,55 @@ +createBucket($bucket); + $result = $ossClient->putObject($bucket, $object, $content); + return $result; + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return false; + } + } +} \ No newline at end of file diff --git a/app/Controller/IndexController.php b/app/Controller/IndexController.php index 3864423..bceb474 100644 --- a/app/Controller/IndexController.php +++ b/app/Controller/IndexController.php @@ -11,6 +11,13 @@ declare(strict_types=1); */ namespace App\Controller; +use Hyperf\HttpServer\Annotation\AutoController; +use League\Flysystem\Filesystem; + +/** + * @AutoController() + * @package App\Controller + */ class IndexController extends AbstractController { public function index() @@ -20,7 +27,24 @@ class IndexController extends AbstractController return [ 'method' => $method, - 'message' => "Hello22222 {$user}.", + 'message' => floatval(2.00), ]; } + + public function example(Filesystem $filesystem) + { + + $file = $this->request->file('upload'); + + var_dump($file);die; + $fileContent = file_get_contents($file->getRealPath()); + var_dump($fileContent);die; + + + + + $stream = fopen($file->getRealPath(),'r+'); + $filesystem->writeStream('uplaods/'.$file->getClientFilename(),$stream); + fclose($stream); + } } diff --git a/app/Controller/StoreController.php b/app/Controller/StoreController.php new file mode 100644 index 0000000..ee8b657 --- /dev/null +++ b/app/Controller/StoreController.php @@ -0,0 +1,73 @@ +request->input('id'); + if (empty($id)){ + return $this->result(1,[],'id不能为空'); + } + $logo = $this->request->input('logo'); + $name = $this->request->input('name'); + $tel = $this->request->input('tel'); + $address = $this->request->input('address'); + $coordinates = $this->request->input('coordinates'); + $capita = $this->request->input('capita'); + $start_at = $this->request->input('start_at'); + $announcement = $this->request->input('announcement'); + $environment = $this->request->input('environment'); + + //>>1上传logo到阿里云oss + //>>2.上传商家环境到阿里云oss + //>>3.保存数据到数据库存 + $fileName = $object = 'public/upload/' . date('Y') . '/' . date('m-d') . '/' . rand(0,9999999999999999).'.jpg'; + $fileUpload = new FileUpload(); + $resLogo = $fileUpload->ossUpload($logo,$fileName); + if (isset($resLogo['info']['http_code'])&&$resLogo['info']['http_code']==200){ + $logo_url = $fileName; + }else{ + return $this->result(1,[]); + } + $res = Db::table('ims_cjdc_store')->where('id',$id)->update([ + 'logo'=>$logo_url??"", + 'name'=>$name, + 'tel'=>$tel, + 'address'=>$address, + 'coordinates'=>$coordinates, + 'capita'=>$capita, + 'start_at'=>$start_at, + 'announcement'=>$announcement, + 'environment'=>$environment, + ]); + return $this->success($res); + + + + + + + + + + + + + + + } +} \ No newline at end of file diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php new file mode 100644 index 0000000..4551b9b --- /dev/null +++ b/app/Controller/TestController.php @@ -0,0 +1,23 @@ +input('id',2); + return (string)$id; + } +} \ No newline at end of file diff --git a/composer.json b/composer.json index 5d55e6c..2a3907c 100644 --- a/composer.json +++ b/composer.json @@ -26,7 +26,9 @@ "hyperf/process": "~2.0.0", "hyperf/redis": "~2.0.0", "hyperf/constants": "~2.0.0", - "hyperf/model-cache": "~2.0.0" + "hyperf/model-cache": "~2.0.0", + "hyperf/filesystem": "^2.0", + "xxtime/flysystem-aliyun-oss": "^1.5" }, "require-dev": { "swoole/ide-helper": "^4.5", From 584fdd683e504199e7a2f9a38233a8b2043d5df1 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 22 Jul 2020 16:32:40 +0800 Subject: [PATCH 002/172] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E4=B8=8D=E5=88=86?= =?UTF-8?q?=E6=B8=A0=E9=81=93=E7=9A=84=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponController.php | 33 +++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/app/Controller/CouponController.php b/app/Controller/CouponController.php index e8b26e2..5ba359d 100644 --- a/app/Controller/CouponController.php +++ b/app/Controller/CouponController.php @@ -34,17 +34,35 @@ class CouponController extends BaseController $this->success(['not_reveive' => []]); } - $c_ids = CouponUserRecType::where('receive_type', $receive_type)->pluck('system_coupon_user_id'); + $c_ids = []; + // 渠道开启,查询该渠道可以领取的优惠券ID + // 渠道未开启,查询所有优惠券 + if (env('SUB_CHANNEL') == 1) { + $c_ids = CouponUserRecType::where('receive_type', $receive_type)->pluck('system_coupon_user_id'); + } else { + $c_ids = Coupon::pluck('id'); + } + $nowTime = time(); - $cr_ids = CouponRec::where([ - ['user_id',"=",$user_id], - ['receive_type',"=",$receive_type] - ])->pluck('system_coupon_user_id'); + + $where = [ + ['user_id',"=",$user_id] + ]; + + // 渠道开启,查询该用户在此渠道领过的优惠券ID + if (env('SUB_CHANNEL') == 1) { + array_push($where, ['receive_type', "=", $receive_type]); + } + + $cr_ids = CouponRec::where($where)->pluck('system_coupon_user_id'); //领过券的ID $c_ids = $c_ids->toArray(); $cr_ids = $cr_ids->toArray(); + // 当前用户可领的优惠券ID + $couponIds = array_diff($c_ids, $cr_ids); + $c = Db::table('ims_system_coupon_user as u') ->where([ ['u.end_time','>',$nowTime], @@ -54,8 +72,9 @@ class CouponController extends BaseController ]) ->join('ims_system_coupon_user_receivetype as type', 'u.id', '=', 'type.system_coupon_user_id') ->whereRaw('u.inventory_use <= u.inventory and u.inventory-u.inventory_use > type.one_receive_number') - ->whereIn('u.id',$c_ids) - ->whereNotIn('u.id',$cr_ids) + // ->whereIn('u.id',$c_ids) + // ->whereNotIn('u.id',$cr_ids) + ->whereIn('u.id', $couponIds) ->select('u.*','type.one_receive_number') ->orderBy('u.weigh','desc') // ->orderByRaw('FIELD(u.id, '.implode(", " , $ids).')') From 28b0f413f5763b68e2f3bb991bbcbd584963f70e Mon Sep 17 00:00:00 2001 From: lanzu_qsy <334039090@qq.com> Date: Wed, 22 Jul 2020 16:34:07 +0800 Subject: [PATCH 003/172] =?UTF-8?q?=E9=87=8D=E5=86=99=E5=B0=8F=E7=A8=8B?= =?UTF-8?q?=E5=BA=8F=E8=8E=B7=E5=8F=96=E9=97=A8=E5=BA=97=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/FileUpload.php | 12 ++-- app/Controller/IndexController.php | 1 - app/Controller/StoreController.php | 105 ++++++++++++++++------------- 3 files changed, 63 insertions(+), 55 deletions(-) diff --git a/app/Controller/FileUpload.php b/app/Controller/FileUpload.php index 0f9f63a..385a02f 100644 --- a/app/Controller/FileUpload.php +++ b/app/Controller/FileUpload.php @@ -15,21 +15,17 @@ class FileUpload extends AbstractController public function __construct() { - - } - - - public function ossUpload($fileContent,$fileName) - { - if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } + } + - //$base64 = input('upload'); + public function ossUpload($fileContent,$fileName) + { $img = base64_decode($fileContent); $accessKeyId = "LTAI4G8QMM97Fg1Gx8TXeast"; $accessKeySecret = "f1KIbMCiO4CXmTzC0FDl6hTRXgFobm"; diff --git a/app/Controller/IndexController.php b/app/Controller/IndexController.php index bceb474..417e4d4 100644 --- a/app/Controller/IndexController.php +++ b/app/Controller/IndexController.php @@ -33,7 +33,6 @@ class IndexController extends AbstractController public function example(Filesystem $filesystem) { - $file = $this->request->file('upload'); var_dump($file);die; diff --git a/app/Controller/StoreController.php b/app/Controller/StoreController.php index ee8b657..30ffa47 100644 --- a/app/Controller/StoreController.php +++ b/app/Controller/StoreController.php @@ -17,55 +17,68 @@ class StoreController extends BaseController { public function infoEdit() { - $id = $this->request->input('id'); - if (empty($id)){ - return $this->result(1,[],'id不能为空'); + if (empty($id)) { + return $this->result(1, [], 'id不能为空'); } - $logo = $this->request->input('logo'); - $name = $this->request->input('name'); - $tel = $this->request->input('tel'); - $address = $this->request->input('address'); - $coordinates = $this->request->input('coordinates'); - $capita = $this->request->input('capita'); - $start_at = $this->request->input('start_at'); - $announcement = $this->request->input('announcement'); - $environment = $this->request->input('environment'); - - //>>1上传logo到阿里云oss - //>>2.上传商家环境到阿里云oss - //>>3.保存数据到数据库存 - $fileName = $object = 'public/upload/' . date('Y') . '/' . date('m-d') . '/' . rand(0,9999999999999999).'.jpg'; - $fileUpload = new FileUpload(); - $resLogo = $fileUpload->ossUpload($logo,$fileName); - if (isset($resLogo['info']['http_code'])&&$resLogo['info']['http_code']==200){ - $logo_url = $fileName; - }else{ - return $this->result(1,[]); + if ($this->request->isMethod('post')) { + $logo = $this->request->input('logo'); + $name = $this->request->input('name'); + $tel = $this->request->input('tel'); + $address = $this->request->input('address'); + $coordinates = $this->request->input('coordinates'); + $capita = $this->request->input('capita'); + $start_at = $this->request->input('start_at'); + $announcement = $this->request->input('announcement'); + $environment = $this->request->input('environment'); + + //>>1上传logo到阿里云oss + //>>2.上传商家环境到阿里云oss + //>>3.保存数据到数据库存 + $fileNameLogo = $object = 'public/upload/' . date('Y') . '/' . date('m-d') . '/' . rand(0, 9999999999999999) . '.jpg'; + $fileUpload = new FileUpload(); + $resLogo = $fileUpload->ossUpload($logo, $fileNameLogo); + if (isset($resLogo['info']['http_code']) && $resLogo['info']['http_code'] == 200) { + $logo_url = $fileNameLogo; + } else { + return $this->result(1, []); + } + $environments = explode(',', $environment); + $envPaths = []; + foreach ($environments as $env) { + $fileNameEnv = $object = 'public/upload/' . date('Y') . '/' . date('m-d') . '/' . rand(0, 9999999999999999) . '.jpg'; + $resEnv = $fileUpload->ossUpload($env, $fileNameEnv); + if (isset($resEnv['info']['http_code']) && $resLogo['info']['http_code'] == 200) { + $envPaths[] = $fileNameEnv; + } + } + if (count($envPaths)) { + $envPath = implode(',', $envPaths); + } + + $res = Db::table('ims_cjdc_store')->where('id', $id)->update([ + 'logo' => $logo_url ?? "", + 'name' => $name, + 'tel' => $tel, + 'address' => $address, + 'coordinates' => $coordinates, + 'capita' => $capita, + 'start_at' => $start_at, + 'announcement' => $announcement, + 'environment' => $envPath ?? "", + ]); + return $this->success($res); } - $res = Db::table('ims_cjdc_store')->where('id',$id)->update([ - 'logo'=>$logo_url??"", - 'name'=>$name, - 'tel'=>$tel, - 'address'=>$address, - 'coordinates'=>$coordinates, - 'capita'=>$capita, - 'start_at'=>$start_at, - 'announcement'=>$announcement, - 'environment'=>$environment, - ]); - return $this->success($res); - - - - - - - - - - - +//'id','name','logo','tel','address','coordinates','capita','start_at','announcement','environment' + //获取店铺信息 + $data = Db::table('ims_cjdc_store') + ->select(['id','name','logo','tel','address','coordinates','capita','start_at','announcement','environment']) + ->where('id',$id) + ->first(); + if ($data){ + $data->site = env('SITE_HOST'); + } + return $this->success($data); From dfe90e7ca4a643f2ca1409c02d06e3291753ab53 Mon Sep 17 00:00:00 2001 From: lanzu_qsy <334039090@qq.com> Date: Wed, 22 Jul 2020 16:53:12 +0800 Subject: [PATCH 004/172] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=9F=9F=E5=90=8D=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/config/config.php b/config/config.php index 7d0c07e..c5ce284 100644 --- a/config/config.php +++ b/config/config.php @@ -28,4 +28,7 @@ return [ LogLevel::WARNING, ], ], + + 'site_host'=>'http://store.api.lanzulive.com/' + ]; From 31db4ffb39fe83aa9ec9368960aea7d6eaaf59dc Mon Sep 17 00:00:00 2001 From: lanzu_qsy <334039090@qq.com> Date: Wed, 22 Jul 2020 16:53:54 +0800 Subject: [PATCH 005/172] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=9F=9F=E5=90=8D?= =?UTF-8?q?=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/StoreController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Controller/StoreController.php b/app/Controller/StoreController.php index 30ffa47..d39decf 100644 --- a/app/Controller/StoreController.php +++ b/app/Controller/StoreController.php @@ -76,7 +76,7 @@ class StoreController extends BaseController ->where('id',$id) ->first(); if ($data){ - $data->site = env('SITE_HOST'); + $data->site = config('site_host'); } return $this->success($data); From 3ae5d4c16b082286bcf62da489410ab99e6ecf4d Mon Sep 17 00:00:00 2001 From: Mike Date: Thu, 23 Jul 2020 11:48:49 +0800 Subject: [PATCH 006/172] =?UTF-8?q?=E6=B7=BB=E5=8A=A0oss=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/TestController.php | 17 +++++- config/autoload/file.php | 94 +++++++++++++++++++++++++++++++ config/routes.php | 4 ++ 3 files changed, 112 insertions(+), 3 deletions(-) create mode 100644 config/autoload/file.php diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index 4551b9b..8b855bb 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -14,10 +14,21 @@ use Hyperf\HttpServer\Annotation\AutoController; */ class TestController extends AbstractController { + private $name = 'default action'; + public function index1(RequestInterface $request) + { + $this->name = 'index1 action'; + return $this->name; + } + + public function index2(RequestInterface $request) + { + $this->name = 'index2 action'; + return $this->name; + } - public function index(RequestInterface $request) + public function index3(RequestInterface $request) { - $id = $request->input('id',2); - return (string)$id; + return $this->name; } } \ No newline at end of file diff --git a/config/autoload/file.php b/config/autoload/file.php new file mode 100644 index 0000000..59cd236 --- /dev/null +++ b/config/autoload/file.php @@ -0,0 +1,94 @@ + 'local', + 'storage' => [ + 'local' => [ + 'driver' => \Hyperf\Filesystem\Adapter\LocalAdapterFactory::class, + 'root' => __DIR__ . '/../../runtime', + ], + 'ftp' => [ + 'driver' => \Hyperf\Filesystem\Adapter\FtpAdapterFactory::class, + 'host' => 'ftp.example.com', + 'username' => 'username', + 'password' => 'password', + // 'port' => 21, + // 'root' => '/path/to/root', + // 'passive' => true, + // 'ssl' => true, + // 'timeout' => 30, + // 'ignorePassiveAddress' => false, + ], + 'memory' => [ + 'driver' => \Hyperf\Filesystem\Adapter\MemoryAdapterFactory::class, + ], + 's3' => [ + 'driver' => \Hyperf\Filesystem\Adapter\S3AdapterFactory::class, + 'credentials' => [ + 'key' => env('S3_KEY'), + 'secret' => env('S3_SECRET'), + ], + 'region' => env('S3_REGION'), + 'version' => 'latest', + 'bucket_endpoint' => false, + 'use_path_style_endpoint' => false, + 'endpoint' => env('S3_ENDPOINT'), + 'bucket_name' => env('S3_BUCKET'), + ], + 'minio' => [ + 'driver' => \Hyperf\Filesystem\Adapter\S3AdapterFactory::class, + 'credentials' => [ + 'key' => env('S3_KEY'), + 'secret' => env('S3_SECRET'), + ], + 'region' => env('S3_REGION'), + 'version' => 'latest', + 'bucket_endpoint' => false, + 'use_path_style_endpoint' => true, + 'endpoint' => env('S3_ENDPOINT'), + 'bucket_name' => env('S3_BUCKET'), + ], + 'oss' => [ + 'driver' => \Hyperf\Filesystem\Adapter\AliyunOssAdapterFactory::class, + 'accessId' => env('OSS_ACCESS_ID'), + 'accessSecret' => env('OSS_ACCESS_SECRET'), + 'bucket' => env('OSS_BUCKET'), + 'endpoint' => env('OSS_ENDPOINT'), + // 'timeout' => 3600, + // 'connectTimeout' => 10, + // 'isCName' => false, + // 'token' => '', + ], + 'qiniu' => [ + 'driver' => \Hyperf\Filesystem\Adapter\QiniuAdapterFactory::class, + 'accessKey' => env('QINIU_ACCESS_KEY'), + 'secretKey' => env('QINIU_SECRET_KEY'), + 'bucket' => env('QINIU_BUCKET'), + 'domain' => env('QINBIU_DOMAIN'), + ], + 'cos' => [ + 'driver' => \Hyperf\Filesystem\Adapter\CosAdapterFactory::class, + 'region' => env('COS_REGION'), + 'credentials' => [ + 'appId' => env('COS_APPID'), + 'secretId' => env('COS_SECRET_ID'), + 'secretKey' => env('COS_SECRET_KEY'), + ], + 'bucket' => env('COS_BUCKET'), + 'read_from_cdn' => false, + // 'timeout' => 60, + // 'connect_timeout' => 60, + // 'cdn' => '', + // 'scheme' => 'https', + ], + ], +]; diff --git a/config/routes.php b/config/routes.php index 10aa6e4..a2e3825 100644 --- a/config/routes.php +++ b/config/routes.php @@ -19,5 +19,9 @@ Router::addGroup('/v1/',function (){ Router::post('CouponUserReceive/getUserReceiveCouponList', 'App\Controller\CouponController@getUserReceiveCouponList'); Router::post('CouponUserReceive/userReceiveCoupon', 'App\Controller\CouponController@userReceiveCoupon'); Router::post('CouponUserReceive/getUserAvailableCoupons', 'App\Controller\CouponController@getUserAvailableCoupons'); + Router::get('test/index1', 'App\Controller\TestController@index1'); + Router::get('test/index2', 'App\Controller\TestController@index2'); + + }); \ No newline at end of file From ab0537a39ad33841e4625cc97619256e8c6ed678 Mon Sep 17 00:00:00 2001 From: Mike Date: Sun, 26 Jul 2020 12:53:19 +0800 Subject: [PATCH 007/172] =?UTF-8?q?=E6=B7=BB=E5=8A=A0ssdb=E4=B8=89?= =?UTF-8?q?=E6=96=B9=E5=BA=93=EF=BC=8C=E6=B7=BB=E5=8A=A0ssdb=20task?= =?UTF-8?q?=E7=BA=BF=E7=A8=8B=E5=BA=94=E7=94=A8=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/TestController.php | 20 +- app/Libs/SimpleSSDB.php | 622 ++++++++++++++++++++++++++++++ app/TaskWorker/SSDBTask.php | 39 ++ composer.json | 3 +- config/autoload/server.php | 4 + config/routes.php | 3 +- 6 files changed, 688 insertions(+), 3 deletions(-) create mode 100644 app/Libs/SimpleSSDB.php create mode 100644 app/TaskWorker/SSDBTask.php diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index 8b855bb..bc034d0 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -6,6 +6,11 @@ namespace App\Controller; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Annotation\AutoController; +use Hyperf\Utils\Coroutine; +use Hyperf\Utils\ApplicationContext; +use Hyperf\Task\TaskExecutor; +use Hyperf\Task\Task; +use App\TaskWorker\SSDBTask; /** * @AutoController() @@ -15,9 +20,22 @@ use Hyperf\HttpServer\Annotation\AutoController; class TestController extends AbstractController { private $name = 'default action'; + + public function index1(RequestInterface $request) { - $this->name = 'index1 action'; + // $container = ApplicationContext::getContainer(); + // $exec = $container->get(TaskExecutor::class); + // $result = $exec->execute(new Task([MethodTask::class, 'handle'], [Coroutine::id()])); + + $client = ApplicationContext::getContainer()->get(SSDBTask::class); + $result = $client->exec("set","bar","1234"); + $result = $client->exec("get","bar"); + + // $client = ApplicationContext::getContainer()->get(MethodTask::class); + // $result = $client->handle("set"); + + $this->name = 'index1 action '. $result; return $this->name; } diff --git a/app/Libs/SimpleSSDB.php b/app/Libs/SimpleSSDB.php new file mode 100644 index 0000000..b6920b2 --- /dev/null +++ b/app/Libs/SimpleSSDB.php @@ -0,0 +1,622 @@ +easy(); + } +} + +class SSDB_Response +{ + public $cmd; + public $code; + public $data = null; + public $message; + + function __construct($code='ok', $data_or_message=null){ + $this->code = $code; + if($code == 'ok'){ + $this->data = $data_or_message; + }else{ + $this->message = $data_or_message; + } + } + + function __toString(){ + if($this->code == 'ok'){ + $s = $this->data === null? '' : json_encode($this->data); + }else{ + $s = $this->message; + } + return sprintf('%-13s %12s %s', $this->cmd, $this->code, $s); + } + + function ok(){ + return $this->code == 'ok'; + } + + function not_found(){ + return $this->code == 'not_found'; + } +} + +// Depricated, use SimpleSSDB instead! +class SSDB +{ + private $debug = false; + public $sock = null; + private $_closed = false; + private $recv_buf = ''; + private $_easy = false; + public $last_resp = null; + + function __construct($host, $port, $timeout_ms=2000){ + $timeout_f = (float)$timeout_ms/1000; + $this->sock = @stream_socket_client("[$host]:$port", $errno, $errstr, $timeout_f); + if(!$this->sock){ + throw new SSDBException("$errno: $errstr"); + } + $timeout_sec = intval($timeout_ms/1000); + $timeout_usec = ($timeout_ms - $timeout_sec * 1000) * 1000; + @stream_set_timeout($this->sock, $timeout_sec, $timeout_usec); + if(function_exists('stream_set_chunk_size')){ + @stream_set_chunk_size($this->sock, 1024 * 1024); + } + } + + function set_timeout($timeout_ms){ + $timeout_sec = intval($timeout_ms/1000); + $timeout_usec = ($timeout_ms - $timeout_sec * 1000) * 1000; + @stream_set_timeout($this->sock, $timeout_sec, $timeout_usec); + } + + /** + * After this method invoked with yesno=true, all requesting methods + * will not return a SSDB_Response object. + * And some certain methods like get/zget will return false + * when response is not ok(not_found, etc) + */ + function easy(){ + $this->_easy = true; + } + + function close(){ + if(!$this->_closed){ + @fclose($this->sock); + $this->_closed = true; + $this->sock = null; + } + } + + function closed(){ + return $this->_closed; + } + + private $batch_mode = false; + private $batch_cmds = array(); + + function batch(){ + $this->batch_mode = true; + $this->batch_cmds = array(); + return $this; + } + + function multi(){ + return $this->batch(); + } + + function exec(){ + $ret = array(); + foreach($this->batch_cmds as $op){ + list($cmd, $params) = $op; + $this->send_req($cmd, $params); + } + foreach($this->batch_cmds as $op){ + list($cmd, $params) = $op; + $resp = $this->recv_resp($cmd, $params); + $resp = $this->check_easy_resp($cmd, $resp); + $ret[] = $resp; + } + $this->batch_mode = false; + $this->batch_cmds = array(); + return $ret; + } + + function request(){ + $args = func_get_args(); + $cmd = array_shift($args); + return $this->__call($cmd, $args); + } + + private $async_auth_password = null; + + function auth($password){ + $this->async_auth_password = $password; + return null; + } + + function __call($cmd, $params=array()){ + $cmd = strtolower($cmd); + if($this->async_auth_password !== null){ + $pass = $this->async_auth_password; + $this->async_auth_password = null; + $auth = $this->__call('auth', array($pass)); + if($auth !== true){ + throw new Exception("Authentication failed"); + } + } + + if($this->batch_mode){ + $this->batch_cmds[] = array($cmd, $params); + return $this; + } + + try{ + if($this->send_req($cmd, $params) === false){ + $resp = new SSDB_Response('error', 'send error'); + }else{ + $resp = $this->recv_resp($cmd, $params); + } + }catch(SSDBException $e){ + if($this->_easy){ + throw $e; + }else{ + $resp = new SSDB_Response('error', $e->getMessage()); + } + } + + if($resp->code == 'noauth'){ + $msg = $resp->message; + throw new Exception($msg); + } + + $resp = $this->check_easy_resp($cmd, $resp); + return $resp; + } + + private function check_easy_resp($cmd, $resp){ + $this->last_resp = $resp; + if($this->_easy){ + if($resp->not_found()){ + return NULL; + }else if(!$resp->ok() && !is_array($resp->data)){ + return false; + }else{ + return $resp->data; + } + }else{ + $resp->cmd = $cmd; + return $resp; + } + } + + function multi_set($kvs=array()){ + $args = array(); + foreach($kvs as $k=>$v){ + $args[] = $k; + $args[] = $v; + } + return $this->__call(__FUNCTION__, $args); + } + + function multi_hset($name, $kvs=array()){ + $args = array($name); + foreach($kvs as $k=>$v){ + $args[] = $k; + $args[] = $v; + } + return $this->__call(__FUNCTION__, $args); + } + + function multi_zset($name, $kvs=array()){ + $args = array($name); + foreach($kvs as $k=>$v){ + $args[] = $k; + $args[] = $v; + } + return $this->__call(__FUNCTION__, $args); + } + + function incr($key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function decr($key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function zincr($name, $key, $score=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function zdecr($name, $key, $score=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function zadd($key, $score, $value){ + $args = array($key, $value, $score); + return $this->__call('zset', $args); + } + + function zRevRank($name, $key){ + $args = func_get_args(); + return $this->__call("zrrank", $args); + } + + function zRevRange($name, $offset, $limit){ + $args = func_get_args(); + return $this->__call("zrrange", $args); + } + + function hincr($name, $key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function hdecr($name, $key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + private function send_req($cmd, $params){ + $req = array($cmd); + foreach($params as $p){ + if(is_array($p)){ + $req = array_merge($req, $p); + }else{ + $req[] = $p; + } + } + return $this->send($req); + } + + private function recv_resp($cmd, $params){ + $resp = $this->recv(); + if($resp === false){ + return new SSDB_Response('error', 'Unknown error'); + }else if(!$resp){ + return new SSDB_Response('disconnected', 'Connection closed'); + } + if($resp[0] == 'noauth'){ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + switch($cmd){ + case 'dbsize': + case 'ping': + case 'qset': + case 'getbit': + case 'setbit': + case 'countbit': + case 'strlen': + case 'set': + case 'setx': + case 'setnx': + case 'zset': + case 'hset': + case 'qpush': + case 'qpush_front': + case 'qpush_back': + case 'qtrim_front': + case 'qtrim_back': + case 'del': + case 'zdel': + case 'hdel': + case 'hsize': + case 'zsize': + case 'qsize': + case 'hclear': + case 'zclear': + case 'qclear': + case 'multi_set': + case 'multi_del': + case 'multi_hset': + case 'multi_hdel': + case 'multi_zset': + case 'multi_zdel': + case 'incr': + case 'decr': + case 'zincr': + case 'zdecr': + case 'hincr': + case 'hdecr': + case 'zget': + case 'zrank': + case 'zrrank': + case 'zcount': + case 'zsum': + case 'zremrangebyrank': + case 'zremrangebyscore': + case 'ttl': + case 'expire': + if($resp[0] == 'ok'){ + $val = isset($resp[1])? intval($resp[1]) : 0; + return new SSDB_Response($resp[0], $val); + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + case 'zavg': + if($resp[0] == 'ok'){ + $val = isset($resp[1])? floatval($resp[1]) : (float)0; + return new SSDB_Response($resp[0], $val); + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + case 'get': + case 'substr': + case 'getset': + case 'hget': + case 'qget': + case 'qfront': + case 'qback': + if($resp[0] == 'ok'){ + if(count($resp) == 2){ + return new SSDB_Response('ok', $resp[1]); + }else{ + return new SSDB_Response('server_error', 'Invalid response'); + } + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + break; + case 'qpop': + case 'qpop_front': + case 'qpop_back': + if($resp[0] == 'ok'){ + $size = 1; + if(isset($params[1])){ + $size = intval($params[1]); + } + if($size <= 1){ + if(count($resp) == 2){ + return new SSDB_Response('ok', $resp[1]); + }else{ + return new SSDB_Response('server_error', 'Invalid response'); + } + }else{ + $data = array_slice($resp, 1); + return new SSDB_Response('ok', $data); + } + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + break; + case 'keys': + case 'zkeys': + case 'hkeys': + case 'hlist': + case 'zlist': + case 'qslice': + if($resp[0] == 'ok'){ + $data = array(); + if($resp[0] == 'ok'){ + $data = array_slice($resp, 1); + } + return new SSDB_Response($resp[0], $data); + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + case 'auth': + case 'exists': + case 'hexists': + case 'zexists': + if($resp[0] == 'ok'){ + if(count($resp) == 2){ + return new SSDB_Response('ok', (bool)$resp[1]); + }else{ + return new SSDB_Response('server_error', 'Invalid response'); + } + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + break; + case 'multi_exists': + case 'multi_hexists': + case 'multi_zexists': + if($resp[0] == 'ok'){ + if(count($resp) % 2 == 1){ + $data = array(); + for($i=1; $idebug){ + echo '> ' . str_replace(array("\r", "\n"), array('\r', '\n'), $s) . "\n"; + } + try{ + while(true){ + $ret = @fwrite($this->sock, $s); + if($ret === false || $ret === 0){ + $this->close(); + throw new SSDBException('Connection lost'); + } + $s = substr($s, $ret); + if(strlen($s) == 0){ + break; + } + @fflush($this->sock); + } + }catch(Exception $e){ + $this->close(); + throw new SSDBException($e->getMessage()); + } + return $ret; + } + + function recv(){ + $this->step = self::STEP_SIZE; + while(true){ + $ret = $this->parse(); + if($ret === null){ + try{ + $data = @fread($this->sock, 1024 * 1024); + if($this->debug){ + echo '< ' . str_replace(array("\r", "\n"), array('\r', '\n'), $data) . "\n"; + } + }catch(Exception $e){ + $data = ''; + } + if($data === false || $data === ''){ + if(feof($this->sock)){ + $this->close(); + throw new SSDBException('Connection lost'); + }else{ + throw new SSDBTimeoutException('Connection timeout'); + } + } + $this->recv_buf .= $data; +# echo "read " . strlen($data) . " total: " . strlen($this->recv_buf) . "\n"; + }else{ + return $ret; + } + } + } + + const STEP_SIZE = 0; + const STEP_DATA = 1; + public $resp = array(); + public $step; + public $block_size; + + private function parse(){ + $spos = 0; + $epos = 0; + $buf_size = strlen($this->recv_buf); + // performance issue for large reponse + //$this->recv_buf = ltrim($this->recv_buf); + while(true){ + $spos = $epos; + if($this->step === self::STEP_SIZE){ + $epos = strpos($this->recv_buf, "\n", $spos); + if($epos === false){ + break; + } + $epos += 1; + $line = substr($this->recv_buf, $spos, $epos - $spos); + $spos = $epos; + + $line = trim($line); + if(strlen($line) == 0){ // head end + $this->recv_buf = substr($this->recv_buf, $spos); + $ret = $this->resp; + $this->resp = array(); + return $ret; + } + $this->block_size = intval($line); + $this->step = self::STEP_DATA; + } + if($this->step === self::STEP_DATA){ + $epos = $spos + $this->block_size; + if($epos <= $buf_size){ + $n = strpos($this->recv_buf, "\n", $epos); + if($n !== false){ + $data = substr($this->recv_buf, $spos, $epos - $spos); + $this->resp[] = $data; + $epos = $n + 1; + $this->step = self::STEP_SIZE; + continue; + } + } + break; + } + } + + // packet not ready + if($spos > 0){ + $this->recv_buf = substr($this->recv_buf, $spos); + } + return null; + } +} \ No newline at end of file diff --git a/app/TaskWorker/SSDBTask.php b/app/TaskWorker/SSDBTask.php new file mode 100644 index 0000000..9c6ef29 --- /dev/null +++ b/app/TaskWorker/SSDBTask.php @@ -0,0 +1,39 @@ +client()->__call($method,$args); + + return $result; + } + + protected function client(){ + if ($this->ss instanceof SimpleSSDB) { + return $this->ss; + } + + $this->ss = new SimpleSSDB(env('SSDB_HOST'), env('SSDB_PORT')); + $this->ss->auth(env('SSDB_AUTH')); + + return $this->ss; + + } +} + diff --git a/composer.json b/composer.json index a7581de..3b9ff4f 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,8 @@ "hyperf/model-cache": "~2.0.0", "hyperf/filesystem": "^2.0", "xxtime/flysystem-aliyun-oss": "^1.5", - "hyperf/validation": "^2.0" + "hyperf/validation": "^2.0", + "hyperf/task": "^2.0" }, "require-dev": { "swoole/ide-helper": "^4.5", diff --git a/config/autoload/server.php b/config/autoload/server.php index d6211cc..f44b083 100644 --- a/config/autoload/server.php +++ b/config/autoload/server.php @@ -36,10 +36,14 @@ return [ 'max_request' => 100000, 'socket_buffer_size' => 2 * 1024 * 1024, 'buffer_output_size' => 2 * 1024 * 1024, + 'task_worker_num' => 8, + 'task_enable_coroutine' => false, ], 'callbacks' => [ SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'], SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'], SwooleEvent::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'], + SwooleEvent::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'], + SwooleEvent::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'], ], ]; diff --git a/config/routes.php b/config/routes.php index 37ec1e2..5e0a183 100644 --- a/config/routes.php +++ b/config/routes.php @@ -22,6 +22,7 @@ Router::addGroup('/v1/',function (){ Router::post('ServiceEvaluate/evaluate', 'App\Controller\ServiceEvaluateController@evaluate'); Router::post('ServiceEvaluate/getPersonnelInfo', 'App\Controller\ServiceEvaluateController@getPersonnelInfo'); Router::post('ServiceEvaluate/getEvaluateList', 'App\Controller\ServiceEvaluateController@getEvaluateList'); - + Router::get('test/index1', 'App\Controller\TestController@index1'); + }); \ No newline at end of file From 720dd8259b5d152b5ca2610f795be16c4188210a Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Mon, 27 Jul 2020 14:58:06 +0800 Subject: [PATCH 008/172] =?UTF-8?q?composer.json=20=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=87=BA=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 7e2cd5a..c9a89d0 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ "hyperf/constants": "~2.0.0", "hyperf/model-cache": "~2.0.0", "hyperf/validation": "^2.0", - "hyperf/paginator": "^2.0" + "hyperf/paginator": "^2.0", "hyperf/filesystem": "^2.0", "xxtime/flysystem-aliyun-oss": "^1.5", "hyperf/validation": "^2.0", From 1957bbfc1159b38f13719c254134bc87e685323a Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Mon, 27 Jul 2020 16:37:13 +0800 Subject: [PATCH 009/172] =?UTF-8?q?=E5=8A=A0=E8=BD=BD=E8=AF=84=E8=AE=BA?= =?UTF-8?q?=E9=BB=98=E8=AE=A4=E9=85=8D=E7=BD=AE=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/ServiceEvaluateController.php | 6 +++--- app/Service/ServiceEvaluateService.php | 7 +++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/app/Controller/ServiceEvaluateController.php b/app/Controller/ServiceEvaluateController.php index 8440f30..edc7ab5 100644 --- a/app/Controller/ServiceEvaluateController.php +++ b/app/Controller/ServiceEvaluateController.php @@ -45,10 +45,10 @@ class ServiceEvaluateController extends BaseController //根据用户iD 获取服务专员详细信息 $service_personnel_id = $this->request->input('service_personnel_id', 0); $res = $this->evaluateService->getPersonnelInfo($service_personnel_id); - //如果存在服务专员则获取默认快捷评价 + //如果存在服务专员则获取配置信息 if(!empty($res)) { - $quick_evaluate = $this->evaluateService->getQuickEvaluate(); - $res->quick_evaluate = $quick_evaluate; + $config = $this->evaluateService->getQuickEvaluate(); + $res->config = $config; } return $this->success($res); } diff --git a/app/Service/ServiceEvaluateService.php b/app/Service/ServiceEvaluateService.php index d7cf885..675feb2 100644 --- a/app/Service/ServiceEvaluateService.php +++ b/app/Service/ServiceEvaluateService.php @@ -51,14 +51,21 @@ class ServiceEvaluateService implements ServiceEvaluateServiceInterface public function getQuickEvaluate() { $data = (object)null; + //获取快速评论标题 $obj1 = (object)null; $obj1->title1 = '服务态度超好'; $obj1->title2 = '服务态度一般般'; $data->quick_evaluate_title = $obj1; + //获取快速评论内容 $obj2 = (object)null; $obj2->content1 = '超级细心'; $obj2->content2 = '马马虎虎'; $data->quick_evaluate_content = $obj2; + //获取评论长度限制参数 + $obj3 = (object)null; + $obj3->min_length = 15; + $obj3->max_length = 150; + $data->length = $obj3; return $data; } From d5e066466c9bdf635fd2935f19232aa487438778 Mon Sep 17 00:00:00 2001 From: weigang Date: Tue, 28 Jul 2020 17:59:08 +0800 Subject: [PATCH 010/172] =?UTF-8?q?=E5=9B=BE=E7=89=87=E3=80=81=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E4=B8=8A=E4=BC=A0=E5=9F=BA=E7=A1=80=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/ErrorCode.php | 15 ++ app/Controller/AttachmentController.php | 68 +++++++ .../Handler/FilesystemExceptionHandler.php | 35 ++++ .../Handler/ValidationExceptionHandler.php | 35 ++++ .../ValidatorFactoryResolvedListener.php | 71 +++++++ app/Request/AttachmentRequest.php | 47 +++++ app/Request/ImageBase64Request.php | 46 +++++ app/Request/ImageRequest.php | 46 +++++ app/Service/AttachmentService.php | 73 ++++++++ app/Service/AttachmentServiceInterface.php | 23 +++ composer.json | 5 +- config/autoload/dependencies.php | 1 + config/autoload/exceptions.php | 2 + config/autoload/file.php | 94 ++++++++++ config/autoload/listeners.php | 1 + config/autoload/middlewares.php | 3 +- config/autoload/server.php | 4 + config/autoload/translation.php | 16 ++ config/routes.php | 4 +- storage/languages/en/validation.php | 177 ++++++++++++++++++ storage/languages/zh_CN/validation.php | 177 ++++++++++++++++++ 21 files changed, 940 insertions(+), 3 deletions(-) create mode 100644 app/Controller/AttachmentController.php create mode 100644 app/Exception/Handler/FilesystemExceptionHandler.php create mode 100644 app/Exception/Handler/ValidationExceptionHandler.php create mode 100644 app/Listener/ValidatorFactoryResolvedListener.php create mode 100644 app/Request/AttachmentRequest.php create mode 100644 app/Request/ImageBase64Request.php create mode 100644 app/Request/ImageRequest.php create mode 100644 app/Service/AttachmentService.php create mode 100644 app/Service/AttachmentServiceInterface.php create mode 100644 config/autoload/file.php create mode 100644 config/autoload/translation.php create mode 100644 storage/languages/en/validation.php create mode 100644 storage/languages/zh_CN/validation.php diff --git a/app/Constants/ErrorCode.php b/app/Constants/ErrorCode.php index 0651e85..1a1dc07 100644 --- a/app/Constants/ErrorCode.php +++ b/app/Constants/ErrorCode.php @@ -23,4 +23,19 @@ class ErrorCode extends AbstractConstants * @Message("Server Error!") */ const SERVER_ERROR = 500; + + /** + * @Message("Params Invalid!") + */ + const PARAMS_INVALID = 900; + + /** + * @Message("Save Failure!") + */ + const SAVE_FAILURE = 100; + + /** + * @Message("文件上传异常") + */ + const UPLOAD_INVALID = 200; } diff --git a/app/Controller/AttachmentController.php b/app/Controller/AttachmentController.php new file mode 100644 index 0000000..efbf45d --- /dev/null +++ b/app/Controller/AttachmentController.php @@ -0,0 +1,68 @@ +request->file('upload'); + $type = $this->request->input('type', ''); + + $fileName = $this->attachmentService->formUpload($file, $type, $filesystem, 'file'); + + return $this->success(['file_path' => $fileName]); + } + + /** + * 单图表单上传 + * @param ImageRequest $request + * @param Filesystem $filesystem + * @return \Psr\Http\Message\ResponseInterface + */ + public function uploadImage(ImageRequest $request, Filesystem $filesystem) + { + $file = $this->request->file('upload'); + $type = $this->request->input('type', ''); + + $fileName = $this->attachmentService->formUpload($file, $type, $filesystem); + + return $this->success(['file_path' => $fileName]); + } + + /** + * 单图base64上传 + * @param ImageBase64Request $request + * @param Filesystem $filesystem + * @return \Psr\Http\Message\ResponseInterface + */ + public function uploadImageByBase64(ImageBase64Request $request, Filesystem $filesystem) + { + $base64Code = $this->request->input('upload'); + $type = $this->request->input('type', ''); + + $fileName = $this->attachmentService->base64Upload($base64Code, $type, $filesystem); + + return $this->success(['file_path' => $fileName]); + } + +} \ No newline at end of file diff --git a/app/Exception/Handler/FilesystemExceptionHandler.php b/app/Exception/Handler/FilesystemExceptionHandler.php new file mode 100644 index 0000000..f5f1b1c --- /dev/null +++ b/app/Exception/Handler/FilesystemExceptionHandler.php @@ -0,0 +1,35 @@ +stopPropagation(); + + $content = json_encode([ + "status" => 'error', + "code" => ErrorCode::UPLOAD_INVALID, + "result" => [], + "message" => $throwable->getMessage() + ]); + + return $response->withHeader('Content-Type', 'application/json') + ->withStatus($throwable->status) + ->withBody(new SwooleStream($content)); + } + + public function isValid(Throwable $throwable): bool + { + return $throwable instanceof FilesystemException; + } +} \ No newline at end of file diff --git a/app/Exception/Handler/ValidationExceptionHandler.php b/app/Exception/Handler/ValidationExceptionHandler.php new file mode 100644 index 0000000..cc2384c --- /dev/null +++ b/app/Exception/Handler/ValidationExceptionHandler.php @@ -0,0 +1,35 @@ +stopPropagation(); + + $content = json_encode([ + "status" => 'error', + "code" => ErrorCode::PARAMS_INVALID, + "result" => [], + "message" => $throwable->validator->errors()->first() + ]); + + return $response->withHeader('Content-Type', 'application/json') + ->withStatus($throwable->status) + ->withBody(new SwooleStream($content)); + } + + public function isValid(Throwable $throwable): bool + { + return $throwable instanceof ValidationException; + } +} \ No newline at end of file diff --git a/app/Listener/ValidatorFactoryResolvedListener.php b/app/Listener/ValidatorFactoryResolvedListener.php new file mode 100644 index 0000000..7e32d66 --- /dev/null +++ b/app/Listener/ValidatorFactoryResolvedListener.php @@ -0,0 +1,71 @@ +validatorFactory; + + // 注册了 nonempty 验证器规则 + $validatorFactory->extend('nonempty', function ($attribute, $value, $parameters, $validator) { + + return isset($value) + && $value + && !empty($value) + && !is_null($value) + && $value != 'undefined' + && $value != 'unknown' + && $value != 'null' + && $value != 'false'; + + }); + + // 注册了 base64 验证器规则 + $validatorFactory->extend('base64', function ($attribute, $value, $parameters, $validator) { + + preg_match('/^(data:\s*image\/(\w+);base64,)/', $value, $result); + + if (empty($result)) { + return false; + } + + if ( + in_array('image', $parameters) + && !in_array($result[2], ['jpg','jpeg','png','gif','svg','bmp']) + ) { + return false; + } + + return true; + + }); + + // 注册了 ext_not_in 验证器规则 + $validatorFactory->extend('ext_not_in', function ($attribute, $value, $parameters, $validator) { + + if (empty($parameters)) { + $parameters = ['', 'php', 'exe', 'sql', 'sh', 'bat', 'py', 'go', 'c', 'cpp']; + } + return !in_array($value->getExtension(), $parameters); + + }); + + } +} \ No newline at end of file diff --git a/app/Request/AttachmentRequest.php b/app/Request/AttachmentRequest.php new file mode 100644 index 0000000..da2e1f0 --- /dev/null +++ b/app/Request/AttachmentRequest.php @@ -0,0 +1,47 @@ + 'required|nonempty|file|ext_not_in', + 'type' => 'nonempty|alpha' + ]; + } + + public function messages(): array + { + return [ + 'upload.required' => '未选择上传的文件', + 'upload.nonempty' => '文件异常', + 'upload.file' => '文件上传不成功', + 'upload.ext_not_in' => '文件不允许上传', + 'type.nonempty' => '文件类型参数异常', + ]; + } + + public function attributes(): array + { + return [ + 'upload' => '文件' + ]; + } +} diff --git a/app/Request/ImageBase64Request.php b/app/Request/ImageBase64Request.php new file mode 100644 index 0000000..88a752a --- /dev/null +++ b/app/Request/ImageBase64Request.php @@ -0,0 +1,46 @@ + 'required|nonempty|base64:image', + 'type' => 'nonempty|alpha' + ]; + } + + public function messages(): array + { + return [ + 'upload.required' => '未选择上传的文件', + 'upload.base64' => '文件不是正常的图片', + 'upload.nonempty' => '文件异常', + 'type.nonempty' => '图片类型参数异常', + ]; + } + + public function attributes(): array + { + return [ + 'upload' => '图片' + ]; + } +} diff --git a/app/Request/ImageRequest.php b/app/Request/ImageRequest.php new file mode 100644 index 0000000..85bad47 --- /dev/null +++ b/app/Request/ImageRequest.php @@ -0,0 +1,46 @@ + 'required|nonempty|file|image', + 'type' => 'nonempty|alpha' + ]; + } + + public function messages(): array + { + return [ + 'upload.required' => '未选择上传的文件', + 'upload.image' => '文件不是正常的图片', + 'upload.nonempty' => '文件异常', + 'type.nonempty' => '图片类型参数异常', + ]; + } + + public function attributes(): array + { + return [ + 'upload' => '图片' + ]; + } +} diff --git a/app/Service/AttachmentService.php b/app/Service/AttachmentService.php new file mode 100644 index 0000000..65ab9a4 --- /dev/null +++ b/app/Service/AttachmentService.php @@ -0,0 +1,73 @@ +getRealPath(); + $fileHash = md5_file($fileRealPath); + + $path = $this->getBasePath($path, $attachmenttype); + $fileName = $path . '/' . $fileHash . '.' . $file->getExtension(); + + $stream = fopen($fileRealPath, 'r+'); + $filesystem->writeStream($fileName, $stream); + fclose($stream); + + return $fileName; + } + + /** + * @inheritDoc + */ + public function base64Upload($contents, $path, $filesystem) + { + + preg_match('/^(data:\s*image\/(\w+);base64,)/', $contents, $result); + if (empty($result)) { + throw new FilesystemNotFoundException(ErrorCode::getMessage(ErrorCode::UPLOAD_INVALID),ErrorCode::UPLOAD_INVALID); + } + + $contents = base64_decode(str_replace($result[1], '', $contents)); + + $fileHash = md5($contents); + $path = $this->getBasePath($path); + $fileName = $path . '/' . $fileHash . '.' . $result[2]; + + $filesystem->write($fileName, $contents); + + return $fileName; + } + + protected function getBasePath($path, $attachmenttype = 'image') + { + switch ($attachmenttype) { + case 'image': + $baseDir = env('IMAGE_BASE', '/attachment/images'); + break; + + case 'file': + $baseDir = env('FILES_BASE', '/attachment/files'); + break; + + default: + $baseDir = env('FILES_BASE', '/attachment'); + break; + } + + $path = $path ? '/'.$path : ''; + $path .= '/'.date('Y').'/'.date('m').'/'.date('d'); + return $baseDir.$path; + } +} \ No newline at end of file diff --git a/app/Service/AttachmentServiceInterface.php b/app/Service/AttachmentServiceInterface.php new file mode 100644 index 0000000..28439b2 --- /dev/null +++ b/app/Service/AttachmentServiceInterface.php @@ -0,0 +1,23 @@ + \App\Service\AttachmentService::class ]; diff --git a/config/autoload/exceptions.php b/config/autoload/exceptions.php index 895bda9..1776a7c 100644 --- a/config/autoload/exceptions.php +++ b/config/autoload/exceptions.php @@ -14,6 +14,8 @@ return [ 'http' => [ Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class, App\Exception\Handler\AppExceptionHandler::class, + \App\Exception\Handler\ValidationExceptionHandler::class, + \App\Exception\Handler\FilesystemExceptionHandler::class, ], ], ]; diff --git a/config/autoload/file.php b/config/autoload/file.php new file mode 100644 index 0000000..6744d66 --- /dev/null +++ b/config/autoload/file.php @@ -0,0 +1,94 @@ + 'oss', + 'storage' => [ + 'local' => [ + 'driver' => \Hyperf\Filesystem\Adapter\LocalAdapterFactory::class, + 'root' => BASE_PATH . '/attachment', + ], + 'ftp' => [ + 'driver' => \Hyperf\Filesystem\Adapter\FtpAdapterFactory::class, + 'host' => 'ftp.example.com', + 'username' => 'username', + 'password' => 'password', + // 'port' => 21, + // 'root' => '/path/to/root', + // 'passive' => true, + // 'ssl' => true, + // 'timeout' => 30, + // 'ignorePassiveAddress' => false, + ], + 'memory' => [ + 'driver' => \Hyperf\Filesystem\Adapter\MemoryAdapterFactory::class, + ], + 's3' => [ + 'driver' => \Hyperf\Filesystem\Adapter\S3AdapterFactory::class, + 'credentials' => [ + 'key' => env('S3_KEY'), + 'secret' => env('S3_SECRET'), + ], + 'region' => env('S3_REGION'), + 'version' => 'latest', + 'bucket_endpoint' => false, + 'use_path_style_endpoint' => false, + 'endpoint' => env('S3_ENDPOINT'), + 'bucket_name' => env('S3_BUCKET'), + ], + 'minio' => [ + 'driver' => \Hyperf\Filesystem\Adapter\S3AdapterFactory::class, + 'credentials' => [ + 'key' => env('S3_KEY'), + 'secret' => env('S3_SECRET'), + ], + 'region' => env('S3_REGION'), + 'version' => 'latest', + 'bucket_endpoint' => false, + 'use_path_style_endpoint' => true, + 'endpoint' => env('S3_ENDPOINT'), + 'bucket_name' => env('S3_BUCKET'), + ], + 'oss' => [ + 'driver' => \Hyperf\Filesystem\Adapter\AliyunOssAdapterFactory::class, + 'accessId' => env('OSS_ACCESS_ID'), + 'accessSecret' => env('OSS_ACCESS_SECRET'), + 'bucket' => env('OSS_BUCKET'), + 'endpoint' => env('OSS_ENDPOINT'), + // 'timeout' => 3600, + // 'connectTimeout' => 10, + // 'isCName' => false, + // 'token' => '', + ], + 'qiniu' => [ + 'driver' => \Hyperf\Filesystem\Adapter\QiniuAdapterFactory::class, + 'accessKey' => env('QINIU_ACCESS_KEY'), + 'secretKey' => env('QINIU_SECRET_KEY'), + 'bucket' => env('QINIU_BUCKET'), + 'domain' => env('QINBIU_DOMAIN'), + ], + 'cos' => [ + 'driver' => \Hyperf\Filesystem\Adapter\CosAdapterFactory::class, + 'region' => env('COS_REGION'), + 'credentials' => [ + 'appId' => env('COS_APPID'), + 'secretId' => env('COS_SECRET_ID'), + 'secretKey' => env('COS_SECRET_KEY'), + ], + 'bucket' => env('COS_BUCKET'), + 'read_from_cdn' => false, + // 'timeout' => 60, + // 'connect_timeout' => 60, + // 'cdn' => '', + // 'scheme' => 'https', + ], + ], +]; diff --git a/config/autoload/listeners.php b/config/autoload/listeners.php index 55b80d5..2741751 100644 --- a/config/autoload/listeners.php +++ b/config/autoload/listeners.php @@ -10,4 +10,5 @@ declare(strict_types=1); * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ return [ + \App\Listener\ValidatorFactoryResolvedListener::class, ]; diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index 8a27adf..2a5ddb0 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -11,6 +11,7 @@ declare(strict_types=1); */ return [ 'http' => [ - \App\Middleware\Auth\ApiMiddleware::class + \App\Middleware\Auth\ApiMiddleware::class, + \Hyperf\Validation\Middleware\ValidationMiddleware::class ], ]; diff --git a/config/autoload/server.php b/config/autoload/server.php index d6211cc..f44b083 100644 --- a/config/autoload/server.php +++ b/config/autoload/server.php @@ -36,10 +36,14 @@ return [ 'max_request' => 100000, 'socket_buffer_size' => 2 * 1024 * 1024, 'buffer_output_size' => 2 * 1024 * 1024, + 'task_worker_num' => 8, + 'task_enable_coroutine' => false, ], 'callbacks' => [ SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'], SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'], SwooleEvent::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'], + SwooleEvent::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'], + SwooleEvent::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'], ], ]; diff --git a/config/autoload/translation.php b/config/autoload/translation.php new file mode 100644 index 0000000..35b9f06 --- /dev/null +++ b/config/autoload/translation.php @@ -0,0 +1,16 @@ + 'zh_CN', + 'fallback_locale' => 'en', + 'path' => BASE_PATH . '/storage/languages', +]; diff --git a/config/routes.php b/config/routes.php index 10aa6e4..2cc6647 100644 --- a/config/routes.php +++ b/config/routes.php @@ -19,5 +19,7 @@ Router::addGroup('/v1/',function (){ Router::post('CouponUserReceive/getUserReceiveCouponList', 'App\Controller\CouponController@getUserReceiveCouponList'); Router::post('CouponUserReceive/userReceiveCoupon', 'App\Controller\CouponController@userReceiveCoupon'); Router::post('CouponUserReceive/getUserAvailableCoupons', 'App\Controller\CouponController@getUserAvailableCoupons'); - + Router::post('Attachment/uploadImage', 'App\Controller\AttachmentController@uploadImage'); + Router::post('Attachment/uploadImageByBase64', 'App\Controller\AttachmentController@uploadImageByBase64'); + Router::post('Attachment/upload', 'App\Controller\AttachmentController@upload'); }); \ No newline at end of file diff --git a/storage/languages/en/validation.php b/storage/languages/en/validation.php new file mode 100644 index 0000000..5e128a6 --- /dev/null +++ b/storage/languages/en/validation.php @@ -0,0 +1,177 @@ + 'The :attribute must be accepted.', + 'active_url' => 'The :attribute is not a valid URL.', + 'after' => 'The :attribute must be a date after :date.', + 'after_or_equal' => 'The :attribute must be a date after or equal to :date.', + 'alpha' => 'The :attribute may only contain letters.', + 'alpha_dash' => 'The :attribute may only contain letters, numbers, and dashes.', + 'alpha_num' => 'The :attribute may only contain letters and numbers.', + 'array' => 'The :attribute must be an array.', + 'before' => 'The :attribute must be a date before :date.', + 'before_or_equal' => 'The :attribute must be a date before or equal to :date.', + 'between' => [ + 'numeric' => 'The :attribute must be between :min and :max.', + 'file' => 'The :attribute must be between :min and :max kilobytes.', + 'string' => 'The :attribute must be between :min and :max characters.', + 'array' => 'The :attribute must have between :min and :max items.', + ], + 'boolean' => 'The :attribute field must be true or false.', + 'confirmed' => 'The :attribute confirmation does not match.', + 'date' => 'The :attribute is not a valid date.', + 'date_format' => 'The :attribute does not match the format :format.', + 'different' => 'The :attribute and :other must be different.', + 'digits' => 'The :attribute must be :digits digits.', + 'digits_between' => 'The :attribute must be between :min and :max digits.', + 'dimensions' => 'The :attribute has invalid image dimensions.', + 'distinct' => 'The :attribute field has a duplicate value.', + 'email' => 'The :attribute must be a valid email address.', + 'exists' => 'The selected :attribute is invalid.', + 'file' => 'The :attribute must be a file.', + 'filled' => 'The :attribute field is required.', + 'gt' => [ + 'numeric' => 'The :attribute must be greater than :value', + 'file' => 'The :attribute must be greater than :value kb', + 'string' => 'The :attribute must be greater than :value characters', + 'array' => 'The :attribute must be greater than :value items', + ], + 'gte' => [ + 'numeric' => 'The :attribute must be great than or equal to :value', + 'file' => 'The :attribute must be great than or equal to :value kb', + 'string' => 'The :attribute must be great than or equal to :value characters', + 'array' => 'The :attribute must be great than or equal to :value items', + ], + 'image' => 'The :attribute must be an image.', + 'in' => 'The selected :attribute is invalid.', + 'in_array' => 'The :attribute field does not exist in :other.', + 'integer' => 'The :attribute must be an integer.', + 'ip' => 'The :attribute must be a valid IP address.', + 'ipv4' => 'The :attribute must be a valid IPv4 address.', + 'ipv6' => 'The :attribute must be a valid IPv6 address.', + 'json' => 'The :attribute must be a valid JSON string.', + 'lt' => [ + 'numeric' => 'The :attribute must be less than :value', + 'file' => 'The :attribute must be less than :value kb', + 'string' => 'The :attribute must be less than :value characters', + 'array' => 'The :attribute must be less than :value items', + ], + 'lte' => [ + 'numeric' => 'The :attribute must be less than or equal to :value', + 'file' => 'The :attribute must be less than or equal to :value kb', + 'string' => 'The :attribute must be less than or equal to :value characters', + 'array' => 'The :attribute must be less than or equal to :value items', + ], + 'max' => [ + 'numeric' => 'The :attribute may not be greater than :max.', + 'file' => 'The :attribute may not be greater than :max kilobytes.', + 'string' => 'The :attribute may not be greater than :max characters.', + 'array' => 'The :attribute may not have more than :max items.', + ], + 'mimes' => 'The :attribute must be a file of type: :values.', + 'mimetypes' => 'The :attribute must be a file of type: :values.', + 'min' => [ + 'numeric' => 'The :attribute must be at least :min.', + 'file' => 'The :attribute must be at least :min kilobytes.', + 'string' => 'The :attribute must be at least :min characters.', + 'array' => 'The :attribute must have at least :min items.', + ], + 'not_in' => 'The selected :attribute is invalid.', + 'not_regex' => 'The :attribute cannot match a given regular rule.', + 'numeric' => 'The :attribute must be a number.', + 'present' => 'The :attribute field must be present.', + 'regex' => 'The :attribute format is invalid.', + 'required' => 'The :attribute field is required.', + 'required_if' => 'The :attribute field is required when :other is :value.', + 'required_unless' => 'The :attribute field is required unless :other is in :values.', + 'required_with' => 'The :attribute field is required when :values is present.', + 'required_with_all' => 'The :attribute field is required when :values is present.', + 'required_without' => 'The :attribute field is required when :values is not present.', + 'required_without_all' => 'The :attribute field is required when none of :values are present.', + 'same' => 'The :attribute and :other must match.', + 'size' => [ + 'numeric' => 'The :attribute must be :size.', + 'file' => 'The :attribute must be :size kilobytes.', + 'string' => 'The :attribute must be :size characters.', + 'array' => 'The :attribute must contain :size items.', + ], + 'starts_with' => 'The :attribute must be start with :values ', + 'string' => 'The :attribute must be a string.', + 'timezone' => 'The :attribute must be a valid zone.', + 'unique' => 'The :attribute has already been taken.', + 'uploaded' => 'The :attribute failed to upload.', + 'url' => 'The :attribute format is invalid.', + 'uuid' => 'The :attribute is invalid UUID.', + 'max_if' => [ + 'numeric' => 'The :attribute may not be greater than :max when :other is :value.', + 'file' => 'The :attribute may not be greater than :max kilobytes when :other is :value.', + 'string' => 'The :attribute may not be greater than :max characters when :other is :value.', + 'array' => 'The :attribute may not have more than :max items when :other is :value.', + ], + 'min_if' => [ + 'numeric' => 'The :attribute must be at least :min when :other is :value.', + 'file' => 'The :attribute must be at least :min kilobytes when :other is :value.', + 'string' => 'The :attribute must be at least :min characters when :other is :value.', + 'array' => 'The :attribute must have at least :min items when :other is :value.', + ], + 'between_if' => [ + 'numeric' => 'The :attribute must be between :min and :max when :other is :value.', + 'file' => 'The :attribute must be between :min and :max kilobytes when :other is :value.', + 'string' => 'The :attribute must be between :min and :max characters when :other is :value.', + 'array' => 'The :attribute must have between :min and :max items when :other is :value.', + ], + /* + |-------------------------------------------------------------------------- + | Custom Validation Language Lines + |-------------------------------------------------------------------------- + | + | Here you may specify custom validation messages for attributes using the + | convention "attribute.rule" to name the lines. This makes it quick to + | specify a specific custom language line for a given attribute rule. + | + */ + + 'custom' => [ + 'attribute-name' => [ + 'rule-name' => 'custom-message', + ], + ], + + /* + |-------------------------------------------------------------------------- + | Custom Validation Attributes + |-------------------------------------------------------------------------- + | + | The following language lines are used to swap attribute place-holders + | with something more reader friendly such as E-Mail Address instead + | of "email". This simply helps us make messages a little cleaner. + | + */ + + 'attributes' => [], + 'phone_number' => 'The :attribute must be a valid phone number', + 'telephone_number' => 'The :attribute must be a valid telephone number', + + 'chinese_word' => 'The :attribute must contain valid characters(chinese/english character, number, underscore)', + 'sequential_array' => 'The :attribute must be sequential array', +]; diff --git a/storage/languages/zh_CN/validation.php b/storage/languages/zh_CN/validation.php new file mode 100644 index 0000000..8093224 --- /dev/null +++ b/storage/languages/zh_CN/validation.php @@ -0,0 +1,177 @@ + ':attribute 必须接受', + 'active_url' => ':attribute 必须是一个合法的 URL', + 'after' => ':attribute 必须是 :date 之后的一个日期', + 'after_or_equal' => ':attribute 必须是 :date 之后或相同的一个日期', + 'alpha' => ':attribute 只能包含字母', + 'alpha_dash' => ':attribute 只能包含字母、数字、中划线或下划线', + 'alpha_num' => ':attribute 只能包含字母和数字', + 'array' => ':attribute 必须是一个数组', + 'before' => ':attribute 必须是 :date 之前的一个日期', + 'before_or_equal' => ':attribute 必须是 :date 之前或相同的一个日期', + 'between' => [ + 'numeric' => ':attribute 必须在 :min 到 :max 之间', + 'file' => ':attribute 必须在 :min 到 :max kb 之间', + 'string' => ':attribute 必须在 :min 到 :max 个字符之间', + 'array' => ':attribute 必须在 :min 到 :max 项之间', + ], + 'boolean' => ':attribute 字符必须是 true 或 false, 1 或 0', + 'confirmed' => ':attribute 二次确认不匹配', + 'date' => ':attribute 必须是一个合法的日期', + 'date_format' => ':attribute 与给定的格式 :format 不符合', + 'different' => ':attribute 必须不同于 :other', + 'digits' => ':attribute 必须是 :digits 位', + 'digits_between' => ':attribute 必须在 :min 和 :max 位之间', + 'dimensions' => ':attribute 具有无效的图片尺寸', + 'distinct' => ':attribute 字段具有重复值', + 'email' => ':attribute 必须是一个合法的电子邮件地址', + 'exists' => '选定的 :attribute 是无效的', + 'file' => ':attribute 必须是一个文件', + 'filled' => ':attribute 的字段是必填的', + 'gt' => [ + 'numeric' => ':attribute 必须大于 :value', + 'file' => ':attribute 必须大于 :value kb', + 'string' => ':attribute 必须大于 :value 个字符', + 'array' => ':attribute 必须大于 :value 项', + ], + 'gte' => [ + 'numeric' => ':attribute 必须大于等于 :value', + 'file' => ':attribute 必须大于等于 :value kb', + 'string' => ':attribute 必须大于等于 :value 个字符', + 'array' => ':attribute 必须大于等于 :value 项', + ], + 'image' => ':attribute 必须是 jpg, jpeg, png, bmp 或者 gif 格式的图片', + 'in' => '选定的 :attribute 是无效的', + 'in_array' => ':attribute 字段不存在于 :other', + 'integer' => ':attribute 必须是个整数', + 'ip' => ':attribute 必须是一个合法的 IP 地址', + 'ipv4' => ':attribute 必须是一个合法的 IPv4 地址', + 'ipv6' => ':attribute 必须是一个合法的 IPv6 地址', + 'json' => ':attribute 必须是一个合法的 JSON 字符串', + 'lt' => [ + 'numeric' => ':attribute 必须小于 :value', + 'file' => ':attribute 必须小于 :value kb', + 'string' => ':attribute 必须小于 :value 个字符', + 'array' => ':attribute 必须小于 :value 项', + ], + 'lte' => [ + 'numeric' => ':attribute 必须小于等于 :value', + 'file' => ':attribute 必须小于等于 :value kb', + 'string' => ':attribute 必须小于等于 :value 个字符', + 'array' => ':attribute 必须小于等于 :value 项', + ], + 'max' => [ + 'numeric' => ':attribute 的最大值为 :max', + 'file' => ':attribute 的最大为 :max kb', + 'string' => ':attribute 的最大长度为 :max 字符', + 'array' => ':attribute 至多有 :max 项', + ], + 'mimes' => ':attribute 的文件类型必须是 :values', + 'mimetypes' => ':attribute 的文件MIME必须是 :values', + 'min' => [ + 'numeric' => ':attribute 的最小值为 :min', + 'file' => ':attribute 大小至少为 :min kb', + 'string' => ':attribute 的最小长度为 :min 字符', + 'array' => ':attribute 至少有 :min 项', + ], + 'not_in' => '选定的 :attribute 是无效的', + 'not_regex' => ':attribute 不能匹配给定的正则', + 'numeric' => ':attribute 必须是数字', + 'present' => ':attribute 字段必须存在', + 'regex' => ':attribute 格式是无效的', + 'required' => ':attribute 字段是必须的', + 'required_if' => ':attribute 字段是必须的当 :other 是 :value', + 'required_unless' => ':attribute 字段是必须的,除非 :other 是在 :values 中', + 'required_with' => ':attribute 字段是必须的当 :values 是存在的', + 'required_with_all' => ':attribute 字段是必须的当 :values 是存在的', + 'required_without' => ':attribute 字段是必须的当 :values 是不存在的', + 'required_without_all' => ':attribute 字段是必须的当 没有一个 :values 是存在的', + 'same' => ':attribute 和 :other 必须匹配', + 'size' => [ + 'numeric' => ':attribute 必须是 :size', + 'file' => ':attribute 必须是 :size kb', + 'string' => ':attribute 必须是 :size 个字符', + 'array' => ':attribute 必须包括 :size 项', + ], + 'starts_with' => ':attribute 必须以 :values 为开头', + 'string' => ':attribute 必须是一个字符串', + 'timezone' => ':attribute 必须是个有效的时区', + 'unique' => ':attribute 已存在', + 'uploaded' => ':attribute 上传失败', + 'url' => ':attribute 无效的格式', + 'uuid' => ':attribute 无效的UUID格式', + 'max_if' => [ + 'numeric' => '当 :other 为 :value 时 :attribute 不能大于 :max', + 'file' => '当 :other 为 :value 时 :attribute 不能大于 :max kb', + 'string' => '当 :other 为 :value 时 :attribute 不能大于 :max 个字符', + 'array' => '当 :other 为 :value 时 :attribute 最多只有 :max 个单元', + ], + 'min_if' => [ + 'numeric' => '当 :other 为 :value 时 :attribute 必须大于等于 :min', + 'file' => '当 :other 为 :value 时 :attribute 大小不能小于 :min kb', + 'string' => '当 :other 为 :value 时 :attribute 至少为 :min 个字符', + 'array' => '当 :other 为 :value 时 :attribute 至少有 :min 个单元', + ], + 'between_if' => [ + 'numeric' => '当 :other 为 :value 时 :attribute 必须介于 :min - :max 之间', + 'file' => '当 :other 为 :value 时 :attribute 必须介于 :min - :max kb 之间', + 'string' => '当 :other 为 :value 时 :attribute 必须介于 :min - :max 个字符之间', + 'array' => '当 :other 为 :value 时 :attribute 必须只有 :min - :max 个单元', + ], + /* + |-------------------------------------------------------------------------- + | Custom Validation Language Lines + |-------------------------------------------------------------------------- + | + | Here you may specify custom validation messages for attributes using the + | convention "attribute.rule" to name the lines. This makes it quick to + | specify a specific custom language line for a given attribute rule. + | + */ + + 'custom' => [ + 'attribute-name' => [ + 'rule-name' => 'custom-message', + ], + ], + + /* + |-------------------------------------------------------------------------- + | Custom Validation Attributes + |-------------------------------------------------------------------------- + | + | The following language lines are used to swap attribute place-holders + | with something more reader friendly such as E-Mail Address instead + | of "email". This simply helps us make messages a little cleaner. + | + */ + + 'attributes' => [], + 'phone_number' => ':attribute 必须为一个有效的电话号码', + 'telephone_number' => ':attribute 必须为一个有效的手机号码', + + 'chinese_word' => ':attribute 必须包含以下有效字符 (中文/英文,数字, 下划线)', + 'sequential_array' => ':attribute 必须是一个有序数组', +]; From c9ab982e686779c51c968ccee30da6b7295f9bd1 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Thu, 30 Jul 2020 16:01:19 +0800 Subject: [PATCH 011/172] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=8E=A7=E5=88=B6?= =?UTF-8?q?=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 28 +++++++++++++++++++++++ config/routes.php | 2 +- 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 app/Controller/CouponRebateController.php diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php new file mode 100644 index 0000000..7ed921d --- /dev/null +++ b/app/Controller/CouponRebateController.php @@ -0,0 +1,28 @@ +success('创建成功'); + } +} diff --git a/config/routes.php b/config/routes.php index 10aa6e4..ef01848 100644 --- a/config/routes.php +++ b/config/routes.php @@ -19,5 +19,5 @@ Router::addGroup('/v1/',function (){ Router::post('CouponUserReceive/getUserReceiveCouponList', 'App\Controller\CouponController@getUserReceiveCouponList'); Router::post('CouponUserReceive/userReceiveCoupon', 'App\Controller\CouponController@userReceiveCoupon'); Router::post('CouponUserReceive/getUserAvailableCoupons', 'App\Controller\CouponController@getUserAvailableCoupons'); - + Router::post('CoupontRebate/isCoupontRebate', 'App\Controller\CouponRebateController@isCouponRebate'); }); \ No newline at end of file From 82cdae3c0241e9033a44f2253c5ec16003254ea9 Mon Sep 17 00:00:00 2001 From: Mike Date: Sun, 26 Jul 2020 12:53:19 +0800 Subject: [PATCH 012/172] =?UTF-8?q?=E5=97=AF=EF=BC=8Cparamstoken=E4=B8=B4?= =?UTF-8?q?=E6=97=B6=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Envoy.blade.php | 6 + app/Controller/ParamsTokenController.php | 28 + app/Controller/TestController.php | 52 ++ app/Libs/SimpleSSDB.php | 622 ++++++++++++++++++++ app/Service/ParamsTokenServiceInterface.php | 11 + app/Service/ParamsTokenSsdbService.php | 17 + app/TaskWorker/SSDBTask.php | 39 ++ composer.json | 6 +- config/autoload/dependencies.php | 1 + config/autoload/server.php | 4 + config/autoload/translation.php | 16 + config/routes.php | 7 +- storage/languages/en/validation.php | 177 ++++++ storage/languages/zh_CN/validation.php | 177 ++++++ 14 files changed, 1161 insertions(+), 2 deletions(-) create mode 100644 app/Controller/ParamsTokenController.php create mode 100644 app/Controller/TestController.php create mode 100644 app/Libs/SimpleSSDB.php create mode 100644 app/Service/ParamsTokenServiceInterface.php create mode 100644 app/Service/ParamsTokenSsdbService.php create mode 100644 app/TaskWorker/SSDBTask.php create mode 100644 config/autoload/translation.php create mode 100644 storage/languages/en/validation.php create mode 100644 storage/languages/zh_CN/validation.php diff --git a/Envoy.blade.php b/Envoy.blade.php index db21e39..39d6cc9 100644 --- a/Envoy.blade.php +++ b/Envoy.blade.php @@ -11,11 +11,17 @@ @task('git_dev') cd /lanzu_api git pull origin develop + @if($composer == true) + composer update --lock + @endif supervisorctl restart lanzu_api @endtask @task('git_prod') cd /lanzu_api git pull origin master + @if($composer == true) + composer update --no-dev --lock + @endif supervisorctl restart lanzu_api @endtask diff --git a/app/Controller/ParamsTokenController.php b/app/Controller/ParamsTokenController.php new file mode 100644 index 0000000..0120c41 --- /dev/null +++ b/app/Controller/ParamsTokenController.php @@ -0,0 +1,28 @@ +paramsTokenService->generate($this->request->all()); + return $this->success($res); + } + + public function analyze() + { + $res = $this->paramsTokenService->analyze($this->request->input('token')); + return $this->success($res); + } +} \ No newline at end of file diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php new file mode 100644 index 0000000..bc034d0 --- /dev/null +++ b/app/Controller/TestController.php @@ -0,0 +1,52 @@ +get(TaskExecutor::class); + // $result = $exec->execute(new Task([MethodTask::class, 'handle'], [Coroutine::id()])); + + $client = ApplicationContext::getContainer()->get(SSDBTask::class); + $result = $client->exec("set","bar","1234"); + $result = $client->exec("get","bar"); + + // $client = ApplicationContext::getContainer()->get(MethodTask::class); + // $result = $client->handle("set"); + + $this->name = 'index1 action '. $result; + return $this->name; + } + + public function index2(RequestInterface $request) + { + $this->name = 'index2 action'; + return $this->name; + } + + public function index3(RequestInterface $request) + { + return $this->name; + } +} \ No newline at end of file diff --git a/app/Libs/SimpleSSDB.php b/app/Libs/SimpleSSDB.php new file mode 100644 index 0000000..b6920b2 --- /dev/null +++ b/app/Libs/SimpleSSDB.php @@ -0,0 +1,622 @@ +easy(); + } +} + +class SSDB_Response +{ + public $cmd; + public $code; + public $data = null; + public $message; + + function __construct($code='ok', $data_or_message=null){ + $this->code = $code; + if($code == 'ok'){ + $this->data = $data_or_message; + }else{ + $this->message = $data_or_message; + } + } + + function __toString(){ + if($this->code == 'ok'){ + $s = $this->data === null? '' : json_encode($this->data); + }else{ + $s = $this->message; + } + return sprintf('%-13s %12s %s', $this->cmd, $this->code, $s); + } + + function ok(){ + return $this->code == 'ok'; + } + + function not_found(){ + return $this->code == 'not_found'; + } +} + +// Depricated, use SimpleSSDB instead! +class SSDB +{ + private $debug = false; + public $sock = null; + private $_closed = false; + private $recv_buf = ''; + private $_easy = false; + public $last_resp = null; + + function __construct($host, $port, $timeout_ms=2000){ + $timeout_f = (float)$timeout_ms/1000; + $this->sock = @stream_socket_client("[$host]:$port", $errno, $errstr, $timeout_f); + if(!$this->sock){ + throw new SSDBException("$errno: $errstr"); + } + $timeout_sec = intval($timeout_ms/1000); + $timeout_usec = ($timeout_ms - $timeout_sec * 1000) * 1000; + @stream_set_timeout($this->sock, $timeout_sec, $timeout_usec); + if(function_exists('stream_set_chunk_size')){ + @stream_set_chunk_size($this->sock, 1024 * 1024); + } + } + + function set_timeout($timeout_ms){ + $timeout_sec = intval($timeout_ms/1000); + $timeout_usec = ($timeout_ms - $timeout_sec * 1000) * 1000; + @stream_set_timeout($this->sock, $timeout_sec, $timeout_usec); + } + + /** + * After this method invoked with yesno=true, all requesting methods + * will not return a SSDB_Response object. + * And some certain methods like get/zget will return false + * when response is not ok(not_found, etc) + */ + function easy(){ + $this->_easy = true; + } + + function close(){ + if(!$this->_closed){ + @fclose($this->sock); + $this->_closed = true; + $this->sock = null; + } + } + + function closed(){ + return $this->_closed; + } + + private $batch_mode = false; + private $batch_cmds = array(); + + function batch(){ + $this->batch_mode = true; + $this->batch_cmds = array(); + return $this; + } + + function multi(){ + return $this->batch(); + } + + function exec(){ + $ret = array(); + foreach($this->batch_cmds as $op){ + list($cmd, $params) = $op; + $this->send_req($cmd, $params); + } + foreach($this->batch_cmds as $op){ + list($cmd, $params) = $op; + $resp = $this->recv_resp($cmd, $params); + $resp = $this->check_easy_resp($cmd, $resp); + $ret[] = $resp; + } + $this->batch_mode = false; + $this->batch_cmds = array(); + return $ret; + } + + function request(){ + $args = func_get_args(); + $cmd = array_shift($args); + return $this->__call($cmd, $args); + } + + private $async_auth_password = null; + + function auth($password){ + $this->async_auth_password = $password; + return null; + } + + function __call($cmd, $params=array()){ + $cmd = strtolower($cmd); + if($this->async_auth_password !== null){ + $pass = $this->async_auth_password; + $this->async_auth_password = null; + $auth = $this->__call('auth', array($pass)); + if($auth !== true){ + throw new Exception("Authentication failed"); + } + } + + if($this->batch_mode){ + $this->batch_cmds[] = array($cmd, $params); + return $this; + } + + try{ + if($this->send_req($cmd, $params) === false){ + $resp = new SSDB_Response('error', 'send error'); + }else{ + $resp = $this->recv_resp($cmd, $params); + } + }catch(SSDBException $e){ + if($this->_easy){ + throw $e; + }else{ + $resp = new SSDB_Response('error', $e->getMessage()); + } + } + + if($resp->code == 'noauth'){ + $msg = $resp->message; + throw new Exception($msg); + } + + $resp = $this->check_easy_resp($cmd, $resp); + return $resp; + } + + private function check_easy_resp($cmd, $resp){ + $this->last_resp = $resp; + if($this->_easy){ + if($resp->not_found()){ + return NULL; + }else if(!$resp->ok() && !is_array($resp->data)){ + return false; + }else{ + return $resp->data; + } + }else{ + $resp->cmd = $cmd; + return $resp; + } + } + + function multi_set($kvs=array()){ + $args = array(); + foreach($kvs as $k=>$v){ + $args[] = $k; + $args[] = $v; + } + return $this->__call(__FUNCTION__, $args); + } + + function multi_hset($name, $kvs=array()){ + $args = array($name); + foreach($kvs as $k=>$v){ + $args[] = $k; + $args[] = $v; + } + return $this->__call(__FUNCTION__, $args); + } + + function multi_zset($name, $kvs=array()){ + $args = array($name); + foreach($kvs as $k=>$v){ + $args[] = $k; + $args[] = $v; + } + return $this->__call(__FUNCTION__, $args); + } + + function incr($key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function decr($key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function zincr($name, $key, $score=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function zdecr($name, $key, $score=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function zadd($key, $score, $value){ + $args = array($key, $value, $score); + return $this->__call('zset', $args); + } + + function zRevRank($name, $key){ + $args = func_get_args(); + return $this->__call("zrrank", $args); + } + + function zRevRange($name, $offset, $limit){ + $args = func_get_args(); + return $this->__call("zrrange", $args); + } + + function hincr($name, $key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function hdecr($name, $key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + private function send_req($cmd, $params){ + $req = array($cmd); + foreach($params as $p){ + if(is_array($p)){ + $req = array_merge($req, $p); + }else{ + $req[] = $p; + } + } + return $this->send($req); + } + + private function recv_resp($cmd, $params){ + $resp = $this->recv(); + if($resp === false){ + return new SSDB_Response('error', 'Unknown error'); + }else if(!$resp){ + return new SSDB_Response('disconnected', 'Connection closed'); + } + if($resp[0] == 'noauth'){ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + switch($cmd){ + case 'dbsize': + case 'ping': + case 'qset': + case 'getbit': + case 'setbit': + case 'countbit': + case 'strlen': + case 'set': + case 'setx': + case 'setnx': + case 'zset': + case 'hset': + case 'qpush': + case 'qpush_front': + case 'qpush_back': + case 'qtrim_front': + case 'qtrim_back': + case 'del': + case 'zdel': + case 'hdel': + case 'hsize': + case 'zsize': + case 'qsize': + case 'hclear': + case 'zclear': + case 'qclear': + case 'multi_set': + case 'multi_del': + case 'multi_hset': + case 'multi_hdel': + case 'multi_zset': + case 'multi_zdel': + case 'incr': + case 'decr': + case 'zincr': + case 'zdecr': + case 'hincr': + case 'hdecr': + case 'zget': + case 'zrank': + case 'zrrank': + case 'zcount': + case 'zsum': + case 'zremrangebyrank': + case 'zremrangebyscore': + case 'ttl': + case 'expire': + if($resp[0] == 'ok'){ + $val = isset($resp[1])? intval($resp[1]) : 0; + return new SSDB_Response($resp[0], $val); + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + case 'zavg': + if($resp[0] == 'ok'){ + $val = isset($resp[1])? floatval($resp[1]) : (float)0; + return new SSDB_Response($resp[0], $val); + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + case 'get': + case 'substr': + case 'getset': + case 'hget': + case 'qget': + case 'qfront': + case 'qback': + if($resp[0] == 'ok'){ + if(count($resp) == 2){ + return new SSDB_Response('ok', $resp[1]); + }else{ + return new SSDB_Response('server_error', 'Invalid response'); + } + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + break; + case 'qpop': + case 'qpop_front': + case 'qpop_back': + if($resp[0] == 'ok'){ + $size = 1; + if(isset($params[1])){ + $size = intval($params[1]); + } + if($size <= 1){ + if(count($resp) == 2){ + return new SSDB_Response('ok', $resp[1]); + }else{ + return new SSDB_Response('server_error', 'Invalid response'); + } + }else{ + $data = array_slice($resp, 1); + return new SSDB_Response('ok', $data); + } + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + break; + case 'keys': + case 'zkeys': + case 'hkeys': + case 'hlist': + case 'zlist': + case 'qslice': + if($resp[0] == 'ok'){ + $data = array(); + if($resp[0] == 'ok'){ + $data = array_slice($resp, 1); + } + return new SSDB_Response($resp[0], $data); + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + case 'auth': + case 'exists': + case 'hexists': + case 'zexists': + if($resp[0] == 'ok'){ + if(count($resp) == 2){ + return new SSDB_Response('ok', (bool)$resp[1]); + }else{ + return new SSDB_Response('server_error', 'Invalid response'); + } + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + break; + case 'multi_exists': + case 'multi_hexists': + case 'multi_zexists': + if($resp[0] == 'ok'){ + if(count($resp) % 2 == 1){ + $data = array(); + for($i=1; $idebug){ + echo '> ' . str_replace(array("\r", "\n"), array('\r', '\n'), $s) . "\n"; + } + try{ + while(true){ + $ret = @fwrite($this->sock, $s); + if($ret === false || $ret === 0){ + $this->close(); + throw new SSDBException('Connection lost'); + } + $s = substr($s, $ret); + if(strlen($s) == 0){ + break; + } + @fflush($this->sock); + } + }catch(Exception $e){ + $this->close(); + throw new SSDBException($e->getMessage()); + } + return $ret; + } + + function recv(){ + $this->step = self::STEP_SIZE; + while(true){ + $ret = $this->parse(); + if($ret === null){ + try{ + $data = @fread($this->sock, 1024 * 1024); + if($this->debug){ + echo '< ' . str_replace(array("\r", "\n"), array('\r', '\n'), $data) . "\n"; + } + }catch(Exception $e){ + $data = ''; + } + if($data === false || $data === ''){ + if(feof($this->sock)){ + $this->close(); + throw new SSDBException('Connection lost'); + }else{ + throw new SSDBTimeoutException('Connection timeout'); + } + } + $this->recv_buf .= $data; +# echo "read " . strlen($data) . " total: " . strlen($this->recv_buf) . "\n"; + }else{ + return $ret; + } + } + } + + const STEP_SIZE = 0; + const STEP_DATA = 1; + public $resp = array(); + public $step; + public $block_size; + + private function parse(){ + $spos = 0; + $epos = 0; + $buf_size = strlen($this->recv_buf); + // performance issue for large reponse + //$this->recv_buf = ltrim($this->recv_buf); + while(true){ + $spos = $epos; + if($this->step === self::STEP_SIZE){ + $epos = strpos($this->recv_buf, "\n", $spos); + if($epos === false){ + break; + } + $epos += 1; + $line = substr($this->recv_buf, $spos, $epos - $spos); + $spos = $epos; + + $line = trim($line); + if(strlen($line) == 0){ // head end + $this->recv_buf = substr($this->recv_buf, $spos); + $ret = $this->resp; + $this->resp = array(); + return $ret; + } + $this->block_size = intval($line); + $this->step = self::STEP_DATA; + } + if($this->step === self::STEP_DATA){ + $epos = $spos + $this->block_size; + if($epos <= $buf_size){ + $n = strpos($this->recv_buf, "\n", $epos); + if($n !== false){ + $data = substr($this->recv_buf, $spos, $epos - $spos); + $this->resp[] = $data; + $epos = $n + 1; + $this->step = self::STEP_SIZE; + continue; + } + } + break; + } + } + + // packet not ready + if($spos > 0){ + $this->recv_buf = substr($this->recv_buf, $spos); + } + return null; + } +} \ No newline at end of file diff --git a/app/Service/ParamsTokenServiceInterface.php b/app/Service/ParamsTokenServiceInterface.php new file mode 100644 index 0000000..440665f --- /dev/null +++ b/app/Service/ParamsTokenServiceInterface.php @@ -0,0 +1,11 @@ + 'zh_cjdianc/pages/couponrebate/index', 'previous_id' => 211, 'is_expired' => 2]; + } +} \ No newline at end of file diff --git a/app/TaskWorker/SSDBTask.php b/app/TaskWorker/SSDBTask.php new file mode 100644 index 0000000..9c6ef29 --- /dev/null +++ b/app/TaskWorker/SSDBTask.php @@ -0,0 +1,39 @@ +client()->__call($method,$args); + + return $result; + } + + protected function client(){ + if ($this->ss instanceof SimpleSSDB) { + return $this->ss; + } + + $this->ss = new SimpleSSDB(env('SSDB_HOST'), env('SSDB_PORT')); + $this->ss->auth(env('SSDB_AUTH')); + + return $this->ss; + + } +} + diff --git a/composer.json b/composer.json index 5d55e6c..3b9ff4f 100644 --- a/composer.json +++ b/composer.json @@ -26,7 +26,11 @@ "hyperf/process": "~2.0.0", "hyperf/redis": "~2.0.0", "hyperf/constants": "~2.0.0", - "hyperf/model-cache": "~2.0.0" + "hyperf/model-cache": "~2.0.0", + "hyperf/filesystem": "^2.0", + "xxtime/flysystem-aliyun-oss": "^1.5", + "hyperf/validation": "^2.0", + "hyperf/task": "^2.0" }, "require-dev": { "swoole/ide-helper": "^4.5", diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 55b80d5..9096061 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -10,4 +10,5 @@ declare(strict_types=1); * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ return [ + \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class ]; diff --git a/config/autoload/server.php b/config/autoload/server.php index d6211cc..f44b083 100644 --- a/config/autoload/server.php +++ b/config/autoload/server.php @@ -36,10 +36,14 @@ return [ 'max_request' => 100000, 'socket_buffer_size' => 2 * 1024 * 1024, 'buffer_output_size' => 2 * 1024 * 1024, + 'task_worker_num' => 8, + 'task_enable_coroutine' => false, ], 'callbacks' => [ SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'], SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'], SwooleEvent::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'], + SwooleEvent::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'], + SwooleEvent::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'], ], ]; diff --git a/config/autoload/translation.php b/config/autoload/translation.php new file mode 100644 index 0000000..35b9f06 --- /dev/null +++ b/config/autoload/translation.php @@ -0,0 +1,16 @@ + 'zh_CN', + 'fallback_locale' => 'en', + 'path' => BASE_PATH . '/storage/languages', +]; diff --git a/config/routes.php b/config/routes.php index ef01848..6e62af4 100644 --- a/config/routes.php +++ b/config/routes.php @@ -19,5 +19,10 @@ Router::addGroup('/v1/',function (){ Router::post('CouponUserReceive/getUserReceiveCouponList', 'App\Controller\CouponController@getUserReceiveCouponList'); Router::post('CouponUserReceive/userReceiveCoupon', 'App\Controller\CouponController@userReceiveCoupon'); Router::post('CouponUserReceive/getUserAvailableCoupons', 'App\Controller\CouponController@getUserAvailableCoupons'); - Router::post('CoupontRebate/isCoupontRebate', 'App\Controller\CouponRebateController@isCouponRebate'); + Router::post('ServiceEvaluate/evaluate', 'App\Controller\ServiceEvaluateController@evaluate'); + Router::post('ServiceEvaluate/getPersonnelInfo', 'App\Controller\ServiceEvaluateController@getPersonnelInfo'); + Router::post('ServiceEvaluate/getEvaluateList', 'App\Controller\ServiceEvaluateController@getEvaluateList'); + Router::get('test/index1', 'App\Controller\TestController@index1'); + Router::POST('ParamsToken/generate', 'App\Controller\ParamsTokenController@generate'); + Router::POST('ParamsToken/analyze', 'App\Controller\ParamsTokenController@analyze'); }); \ No newline at end of file diff --git a/storage/languages/en/validation.php b/storage/languages/en/validation.php new file mode 100644 index 0000000..5e128a6 --- /dev/null +++ b/storage/languages/en/validation.php @@ -0,0 +1,177 @@ + 'The :attribute must be accepted.', + 'active_url' => 'The :attribute is not a valid URL.', + 'after' => 'The :attribute must be a date after :date.', + 'after_or_equal' => 'The :attribute must be a date after or equal to :date.', + 'alpha' => 'The :attribute may only contain letters.', + 'alpha_dash' => 'The :attribute may only contain letters, numbers, and dashes.', + 'alpha_num' => 'The :attribute may only contain letters and numbers.', + 'array' => 'The :attribute must be an array.', + 'before' => 'The :attribute must be a date before :date.', + 'before_or_equal' => 'The :attribute must be a date before or equal to :date.', + 'between' => [ + 'numeric' => 'The :attribute must be between :min and :max.', + 'file' => 'The :attribute must be between :min and :max kilobytes.', + 'string' => 'The :attribute must be between :min and :max characters.', + 'array' => 'The :attribute must have between :min and :max items.', + ], + 'boolean' => 'The :attribute field must be true or false.', + 'confirmed' => 'The :attribute confirmation does not match.', + 'date' => 'The :attribute is not a valid date.', + 'date_format' => 'The :attribute does not match the format :format.', + 'different' => 'The :attribute and :other must be different.', + 'digits' => 'The :attribute must be :digits digits.', + 'digits_between' => 'The :attribute must be between :min and :max digits.', + 'dimensions' => 'The :attribute has invalid image dimensions.', + 'distinct' => 'The :attribute field has a duplicate value.', + 'email' => 'The :attribute must be a valid email address.', + 'exists' => 'The selected :attribute is invalid.', + 'file' => 'The :attribute must be a file.', + 'filled' => 'The :attribute field is required.', + 'gt' => [ + 'numeric' => 'The :attribute must be greater than :value', + 'file' => 'The :attribute must be greater than :value kb', + 'string' => 'The :attribute must be greater than :value characters', + 'array' => 'The :attribute must be greater than :value items', + ], + 'gte' => [ + 'numeric' => 'The :attribute must be great than or equal to :value', + 'file' => 'The :attribute must be great than or equal to :value kb', + 'string' => 'The :attribute must be great than or equal to :value characters', + 'array' => 'The :attribute must be great than or equal to :value items', + ], + 'image' => 'The :attribute must be an image.', + 'in' => 'The selected :attribute is invalid.', + 'in_array' => 'The :attribute field does not exist in :other.', + 'integer' => 'The :attribute must be an integer.', + 'ip' => 'The :attribute must be a valid IP address.', + 'ipv4' => 'The :attribute must be a valid IPv4 address.', + 'ipv6' => 'The :attribute must be a valid IPv6 address.', + 'json' => 'The :attribute must be a valid JSON string.', + 'lt' => [ + 'numeric' => 'The :attribute must be less than :value', + 'file' => 'The :attribute must be less than :value kb', + 'string' => 'The :attribute must be less than :value characters', + 'array' => 'The :attribute must be less than :value items', + ], + 'lte' => [ + 'numeric' => 'The :attribute must be less than or equal to :value', + 'file' => 'The :attribute must be less than or equal to :value kb', + 'string' => 'The :attribute must be less than or equal to :value characters', + 'array' => 'The :attribute must be less than or equal to :value items', + ], + 'max' => [ + 'numeric' => 'The :attribute may not be greater than :max.', + 'file' => 'The :attribute may not be greater than :max kilobytes.', + 'string' => 'The :attribute may not be greater than :max characters.', + 'array' => 'The :attribute may not have more than :max items.', + ], + 'mimes' => 'The :attribute must be a file of type: :values.', + 'mimetypes' => 'The :attribute must be a file of type: :values.', + 'min' => [ + 'numeric' => 'The :attribute must be at least :min.', + 'file' => 'The :attribute must be at least :min kilobytes.', + 'string' => 'The :attribute must be at least :min characters.', + 'array' => 'The :attribute must have at least :min items.', + ], + 'not_in' => 'The selected :attribute is invalid.', + 'not_regex' => 'The :attribute cannot match a given regular rule.', + 'numeric' => 'The :attribute must be a number.', + 'present' => 'The :attribute field must be present.', + 'regex' => 'The :attribute format is invalid.', + 'required' => 'The :attribute field is required.', + 'required_if' => 'The :attribute field is required when :other is :value.', + 'required_unless' => 'The :attribute field is required unless :other is in :values.', + 'required_with' => 'The :attribute field is required when :values is present.', + 'required_with_all' => 'The :attribute field is required when :values is present.', + 'required_without' => 'The :attribute field is required when :values is not present.', + 'required_without_all' => 'The :attribute field is required when none of :values are present.', + 'same' => 'The :attribute and :other must match.', + 'size' => [ + 'numeric' => 'The :attribute must be :size.', + 'file' => 'The :attribute must be :size kilobytes.', + 'string' => 'The :attribute must be :size characters.', + 'array' => 'The :attribute must contain :size items.', + ], + 'starts_with' => 'The :attribute must be start with :values ', + 'string' => 'The :attribute must be a string.', + 'timezone' => 'The :attribute must be a valid zone.', + 'unique' => 'The :attribute has already been taken.', + 'uploaded' => 'The :attribute failed to upload.', + 'url' => 'The :attribute format is invalid.', + 'uuid' => 'The :attribute is invalid UUID.', + 'max_if' => [ + 'numeric' => 'The :attribute may not be greater than :max when :other is :value.', + 'file' => 'The :attribute may not be greater than :max kilobytes when :other is :value.', + 'string' => 'The :attribute may not be greater than :max characters when :other is :value.', + 'array' => 'The :attribute may not have more than :max items when :other is :value.', + ], + 'min_if' => [ + 'numeric' => 'The :attribute must be at least :min when :other is :value.', + 'file' => 'The :attribute must be at least :min kilobytes when :other is :value.', + 'string' => 'The :attribute must be at least :min characters when :other is :value.', + 'array' => 'The :attribute must have at least :min items when :other is :value.', + ], + 'between_if' => [ + 'numeric' => 'The :attribute must be between :min and :max when :other is :value.', + 'file' => 'The :attribute must be between :min and :max kilobytes when :other is :value.', + 'string' => 'The :attribute must be between :min and :max characters when :other is :value.', + 'array' => 'The :attribute must have between :min and :max items when :other is :value.', + ], + /* + |-------------------------------------------------------------------------- + | Custom Validation Language Lines + |-------------------------------------------------------------------------- + | + | Here you may specify custom validation messages for attributes using the + | convention "attribute.rule" to name the lines. This makes it quick to + | specify a specific custom language line for a given attribute rule. + | + */ + + 'custom' => [ + 'attribute-name' => [ + 'rule-name' => 'custom-message', + ], + ], + + /* + |-------------------------------------------------------------------------- + | Custom Validation Attributes + |-------------------------------------------------------------------------- + | + | The following language lines are used to swap attribute place-holders + | with something more reader friendly such as E-Mail Address instead + | of "email". This simply helps us make messages a little cleaner. + | + */ + + 'attributes' => [], + 'phone_number' => 'The :attribute must be a valid phone number', + 'telephone_number' => 'The :attribute must be a valid telephone number', + + 'chinese_word' => 'The :attribute must contain valid characters(chinese/english character, number, underscore)', + 'sequential_array' => 'The :attribute must be sequential array', +]; diff --git a/storage/languages/zh_CN/validation.php b/storage/languages/zh_CN/validation.php new file mode 100644 index 0000000..8093224 --- /dev/null +++ b/storage/languages/zh_CN/validation.php @@ -0,0 +1,177 @@ + ':attribute 必须接受', + 'active_url' => ':attribute 必须是一个合法的 URL', + 'after' => ':attribute 必须是 :date 之后的一个日期', + 'after_or_equal' => ':attribute 必须是 :date 之后或相同的一个日期', + 'alpha' => ':attribute 只能包含字母', + 'alpha_dash' => ':attribute 只能包含字母、数字、中划线或下划线', + 'alpha_num' => ':attribute 只能包含字母和数字', + 'array' => ':attribute 必须是一个数组', + 'before' => ':attribute 必须是 :date 之前的一个日期', + 'before_or_equal' => ':attribute 必须是 :date 之前或相同的一个日期', + 'between' => [ + 'numeric' => ':attribute 必须在 :min 到 :max 之间', + 'file' => ':attribute 必须在 :min 到 :max kb 之间', + 'string' => ':attribute 必须在 :min 到 :max 个字符之间', + 'array' => ':attribute 必须在 :min 到 :max 项之间', + ], + 'boolean' => ':attribute 字符必须是 true 或 false, 1 或 0', + 'confirmed' => ':attribute 二次确认不匹配', + 'date' => ':attribute 必须是一个合法的日期', + 'date_format' => ':attribute 与给定的格式 :format 不符合', + 'different' => ':attribute 必须不同于 :other', + 'digits' => ':attribute 必须是 :digits 位', + 'digits_between' => ':attribute 必须在 :min 和 :max 位之间', + 'dimensions' => ':attribute 具有无效的图片尺寸', + 'distinct' => ':attribute 字段具有重复值', + 'email' => ':attribute 必须是一个合法的电子邮件地址', + 'exists' => '选定的 :attribute 是无效的', + 'file' => ':attribute 必须是一个文件', + 'filled' => ':attribute 的字段是必填的', + 'gt' => [ + 'numeric' => ':attribute 必须大于 :value', + 'file' => ':attribute 必须大于 :value kb', + 'string' => ':attribute 必须大于 :value 个字符', + 'array' => ':attribute 必须大于 :value 项', + ], + 'gte' => [ + 'numeric' => ':attribute 必须大于等于 :value', + 'file' => ':attribute 必须大于等于 :value kb', + 'string' => ':attribute 必须大于等于 :value 个字符', + 'array' => ':attribute 必须大于等于 :value 项', + ], + 'image' => ':attribute 必须是 jpg, jpeg, png, bmp 或者 gif 格式的图片', + 'in' => '选定的 :attribute 是无效的', + 'in_array' => ':attribute 字段不存在于 :other', + 'integer' => ':attribute 必须是个整数', + 'ip' => ':attribute 必须是一个合法的 IP 地址', + 'ipv4' => ':attribute 必须是一个合法的 IPv4 地址', + 'ipv6' => ':attribute 必须是一个合法的 IPv6 地址', + 'json' => ':attribute 必须是一个合法的 JSON 字符串', + 'lt' => [ + 'numeric' => ':attribute 必须小于 :value', + 'file' => ':attribute 必须小于 :value kb', + 'string' => ':attribute 必须小于 :value 个字符', + 'array' => ':attribute 必须小于 :value 项', + ], + 'lte' => [ + 'numeric' => ':attribute 必须小于等于 :value', + 'file' => ':attribute 必须小于等于 :value kb', + 'string' => ':attribute 必须小于等于 :value 个字符', + 'array' => ':attribute 必须小于等于 :value 项', + ], + 'max' => [ + 'numeric' => ':attribute 的最大值为 :max', + 'file' => ':attribute 的最大为 :max kb', + 'string' => ':attribute 的最大长度为 :max 字符', + 'array' => ':attribute 至多有 :max 项', + ], + 'mimes' => ':attribute 的文件类型必须是 :values', + 'mimetypes' => ':attribute 的文件MIME必须是 :values', + 'min' => [ + 'numeric' => ':attribute 的最小值为 :min', + 'file' => ':attribute 大小至少为 :min kb', + 'string' => ':attribute 的最小长度为 :min 字符', + 'array' => ':attribute 至少有 :min 项', + ], + 'not_in' => '选定的 :attribute 是无效的', + 'not_regex' => ':attribute 不能匹配给定的正则', + 'numeric' => ':attribute 必须是数字', + 'present' => ':attribute 字段必须存在', + 'regex' => ':attribute 格式是无效的', + 'required' => ':attribute 字段是必须的', + 'required_if' => ':attribute 字段是必须的当 :other 是 :value', + 'required_unless' => ':attribute 字段是必须的,除非 :other 是在 :values 中', + 'required_with' => ':attribute 字段是必须的当 :values 是存在的', + 'required_with_all' => ':attribute 字段是必须的当 :values 是存在的', + 'required_without' => ':attribute 字段是必须的当 :values 是不存在的', + 'required_without_all' => ':attribute 字段是必须的当 没有一个 :values 是存在的', + 'same' => ':attribute 和 :other 必须匹配', + 'size' => [ + 'numeric' => ':attribute 必须是 :size', + 'file' => ':attribute 必须是 :size kb', + 'string' => ':attribute 必须是 :size 个字符', + 'array' => ':attribute 必须包括 :size 项', + ], + 'starts_with' => ':attribute 必须以 :values 为开头', + 'string' => ':attribute 必须是一个字符串', + 'timezone' => ':attribute 必须是个有效的时区', + 'unique' => ':attribute 已存在', + 'uploaded' => ':attribute 上传失败', + 'url' => ':attribute 无效的格式', + 'uuid' => ':attribute 无效的UUID格式', + 'max_if' => [ + 'numeric' => '当 :other 为 :value 时 :attribute 不能大于 :max', + 'file' => '当 :other 为 :value 时 :attribute 不能大于 :max kb', + 'string' => '当 :other 为 :value 时 :attribute 不能大于 :max 个字符', + 'array' => '当 :other 为 :value 时 :attribute 最多只有 :max 个单元', + ], + 'min_if' => [ + 'numeric' => '当 :other 为 :value 时 :attribute 必须大于等于 :min', + 'file' => '当 :other 为 :value 时 :attribute 大小不能小于 :min kb', + 'string' => '当 :other 为 :value 时 :attribute 至少为 :min 个字符', + 'array' => '当 :other 为 :value 时 :attribute 至少有 :min 个单元', + ], + 'between_if' => [ + 'numeric' => '当 :other 为 :value 时 :attribute 必须介于 :min - :max 之间', + 'file' => '当 :other 为 :value 时 :attribute 必须介于 :min - :max kb 之间', + 'string' => '当 :other 为 :value 时 :attribute 必须介于 :min - :max 个字符之间', + 'array' => '当 :other 为 :value 时 :attribute 必须只有 :min - :max 个单元', + ], + /* + |-------------------------------------------------------------------------- + | Custom Validation Language Lines + |-------------------------------------------------------------------------- + | + | Here you may specify custom validation messages for attributes using the + | convention "attribute.rule" to name the lines. This makes it quick to + | specify a specific custom language line for a given attribute rule. + | + */ + + 'custom' => [ + 'attribute-name' => [ + 'rule-name' => 'custom-message', + ], + ], + + /* + |-------------------------------------------------------------------------- + | Custom Validation Attributes + |-------------------------------------------------------------------------- + | + | The following language lines are used to swap attribute place-holders + | with something more reader friendly such as E-Mail Address instead + | of "email". This simply helps us make messages a little cleaner. + | + */ + + 'attributes' => [], + 'phone_number' => ':attribute 必须为一个有效的电话号码', + 'telephone_number' => ':attribute 必须为一个有效的手机号码', + + 'chinese_word' => ':attribute 必须包含以下有效字符 (中文/英文,数字, 下划线)', + 'sequential_array' => ':attribute 必须是一个有序数组', +]; From 1b5a51e1ad9cc63c336a1657db71df979ad501a3 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 30 Jul 2020 18:42:28 +0800 Subject: [PATCH 013/172] =?UTF-8?q?=E5=A4=84=E7=90=86=E8=B7=A8=E5=9F=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Middleware/CorsMiddleware.php | 34 +++++++++++++++++++++++++++++++ config/autoload/middlewares.php | 3 ++- config/routes.php | 4 ++-- 3 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 app/Middleware/CorsMiddleware.php diff --git a/app/Middleware/CorsMiddleware.php b/app/Middleware/CorsMiddleware.php new file mode 100644 index 0000000..7fb6495 --- /dev/null +++ b/app/Middleware/CorsMiddleware.php @@ -0,0 +1,34 @@ +withHeader('Access-Control-Allow-Origin', '*') + ->withHeader('Access-Control-Allow-Credentials', 'true') + // Headers 可以根据实际情况进行改写。 + ->withHeader('Access-Control-Allow-Headers', 'DNT,Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization'); + + Context::set(ResponseInterface::class, $response); + + if ($request->getMethod() == 'OPTIONS') { + return $response; + } + + return $handler->handle($request); + } +} \ No newline at end of file diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index 8a27adf..292a74a 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -11,6 +11,7 @@ declare(strict_types=1); */ return [ 'http' => [ - \App\Middleware\Auth\ApiMiddleware::class + \App\Middleware\Auth\ApiMiddleware::class, + \App\Middleware\CorsMiddleware::class, ], ]; diff --git a/config/routes.php b/config/routes.php index 6e62af4..88b8a99 100644 --- a/config/routes.php +++ b/config/routes.php @@ -23,6 +23,6 @@ Router::addGroup('/v1/',function (){ Router::post('ServiceEvaluate/getPersonnelInfo', 'App\Controller\ServiceEvaluateController@getPersonnelInfo'); Router::post('ServiceEvaluate/getEvaluateList', 'App\Controller\ServiceEvaluateController@getEvaluateList'); Router::get('test/index1', 'App\Controller\TestController@index1'); - Router::POST('ParamsToken/generate', 'App\Controller\ParamsTokenController@generate'); - Router::POST('ParamsToken/analyze', 'App\Controller\ParamsTokenController@analyze'); + Router::post('ParamsToken/generate', 'App\Controller\ParamsTokenController@generate'); + Router::post('ParamsToken/analyze', 'App\Controller\ParamsTokenController@analyze'); }); \ No newline at end of file From cb16f46f1a18fef2e4409a5fbee728a59fa43b36 Mon Sep 17 00:00:00 2001 From: Mike Date: Sat, 1 Aug 2020 19:47:38 +0800 Subject: [PATCH 014/172] add ali iot vendor --- app/Controller/TestController.php | 10 +++- app/TaskWorker/AliIotTask.php | 91 +++++++++++++++++++++++++++++++ app/TaskWorker/PubRequest.php | 56 +++++++++++++++++++ composer.json | 4 +- 4 files changed, 156 insertions(+), 5 deletions(-) create mode 100644 app/TaskWorker/AliIotTask.php create mode 100644 app/TaskWorker/PubRequest.php diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index bc034d0..78c2327 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -11,6 +11,7 @@ use Hyperf\Utils\ApplicationContext; use Hyperf\Task\TaskExecutor; use Hyperf\Task\Task; use App\TaskWorker\SSDBTask; +use App\TaskWorker\AliIotTask; /** * @AutoController() @@ -28,9 +29,12 @@ class TestController extends AbstractController // $exec = $container->get(TaskExecutor::class); // $result = $exec->execute(new Task([MethodTask::class, 'handle'], [Coroutine::id()])); - $client = ApplicationContext::getContainer()->get(SSDBTask::class); - $result = $client->exec("set","bar","1234"); - $result = $client->exec("get","bar"); + // $client = ApplicationContext::getContainer()->get(SSDBTask::class); + // $result = $client->exec("set","bar","1234"); + // $result = $client->exec("get","bar"); + $client = ApplicationContext::getContainer()->get(AliIotTask::class); + + $client->exec("set","bar","1234"); // $client = ApplicationContext::getContainer()->get(MethodTask::class); // $result = $client->handle("set"); diff --git a/app/TaskWorker/AliIotTask.php b/app/TaskWorker/AliIotTask.php new file mode 100644 index 0000000..e629137 --- /dev/null +++ b/app/TaskWorker/AliIotTask.php @@ -0,0 +1,91 @@ +regionId('cn-shanghai') + ->asDefaultClient(); + $result2 = ''; + + $msg = "{\"msg\":\"收款123元\"}"; + try{ + AlibabaCloud::rpc() + ->product('Iot') + // ->scheme('https') // https | http + ->version('2018-01-20') + ->action('Pub') + ->method('POST') + ->host('iot.cn-shanghai.aliyuncs.com') + ->options([ + 'query' => [ + 'RegionId' => "cn-shanghai", + 'TopicFullName' => "/a1ZSurIJmO0/BOX0000000000003/user/get", + 'MessageContent' => base64_encode($msg), + 'ProductKey' => "a1ZSurIJmO0", + ], + ]) + ->request(); + //var_dump($result2->toArray()); + } catch (ClientException $e) { + echo $e->getErrorMessage() . PHP_EOL; + } catch (ServerException $e) { + echo $e->getErrorMessage() . PHP_EOL; + } + + //print_r($response); + return ""; + } + +// protected function getClient(){ +// AlibabaCloud::accessKeyClient('LTAI4GJEWrN6dVh7HmPKHMyF', 'wMae4ckfVGwMQPVw5ZlVDDpihVeUap') +// ->regionId('cn-shanghai') +// ->asDefaultClient(); +// $result = ''; + +// $msg = "{\"msg\":\"收款123元\"}"; +// try{ +// $result = AlibabaCloud::rpc() +// ->product('Iot') +// // ->scheme('https') // https | http +// ->version('2018-01-20') +// ->action('Pub') +// ->method('POST') +// ->host('iot.cn-shanghai.aliyuncs.com') +// ->options([ +// 'query' => [ +// 'RegionId' => "cn-shanghai", +// 'TopicFullName' => "/a1ZSurIJmO0/BOX0000000000003/user/get", +// 'MessageContent' => base64_encode($msg), +// 'ProductKey' => "a1ZSurIJmO0", +// ], +// ]) +// ->request(); +// var_dump($result->toArray()); +// } catch (ClientException $e) { +// echo $e->getErrorMessage() . PHP_EOL; +// } catch (ServerException $e) { +// echo $e->getErrorMessage() . PHP_EOL; +// } +// return $result; + +// } +} + diff --git a/app/TaskWorker/PubRequest.php b/app/TaskWorker/PubRequest.php new file mode 100644 index 0000000..e784ee1 --- /dev/null +++ b/app/TaskWorker/PubRequest.php @@ -0,0 +1,56 @@ +setMethod("POST"); + } + + private $topicFullName; + + private $qos; + + private $messageContent; + + private $productKey; + + public function getTopicFullName() { + return $this->topicFullName; + } + + public function setTopicFullName($topicFullName) { + $this->topicFullName = $topicFullName; + $this->queryParameters["TopicFullName"]=$topicFullName; + } + + public function getQos() { + return $this->qos; + } + + public function setQos($qos) { + $this->qos = $qos; + $this->queryParameters["Qos"]=$qos; + } + + public function getMessageContent() { + return $this->messageContent; + } + + public function setMessageContent($messageContent) { + $this->messageContent = $messageContent; + $this->queryParameters["MessageContent"]=$messageContent; + } + + public function getProductKey() { + return $this->productKey; + } + + public function setProductKey($productKey) { + $this->productKey = $productKey; + $this->queryParameters["ProductKey"]=$productKey; + } + +} \ No newline at end of file diff --git a/composer.json b/composer.json index c9a89d0..0910063 100644 --- a/composer.json +++ b/composer.json @@ -31,8 +31,8 @@ "hyperf/paginator": "^2.0", "hyperf/filesystem": "^2.0", "xxtime/flysystem-aliyun-oss": "^1.5", - "hyperf/validation": "^2.0", - "hyperf/task": "^2.0" + "hyperf/task": "^2.0", + "alibabacloud/iot": "^1.8" }, "require-dev": { "swoole/ide-helper": "^4.5", From 9bd0f9b2166785d6c3bdd064f48824a4f34278e0 Mon Sep 17 00:00:00 2001 From: Mike Date: Sun, 2 Aug 2020 16:38:15 +0800 Subject: [PATCH 015/172] =?UTF-8?q?=E5=88=9B=E5=BB=BA=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Commons/Log.php | 88 +++++++++++++++++++++++++++ app/Controller/AbstractController.php | 8 +++ app/Controller/TestController.php | 16 +++-- composer.json | 3 +- config/autoload/dependencies.php | 1 + 5 files changed, 110 insertions(+), 6 deletions(-) create mode 100644 app/Commons/Log.php diff --git a/app/Commons/Log.php b/app/Commons/Log.php new file mode 100644 index 0000000..bf5fb24 --- /dev/null +++ b/app/Commons/Log.php @@ -0,0 +1,88 @@ +clientFactory = $clientFactory; + } + + public function getClient() + { + // $options 等同于 GuzzleHttp\Client 构造函数的 $config 参数 + $options = [ + 'timeout' => 2.0, + ]; + // $client 为协程化的 GuzzleHttp\Client 对象 + $client = $this->clientFactory->create($options); + + return $client; + } + + public function event($labels=null,$datas){ + + co(function () use ($labels,$datas){ + + $client = $this->getClient(); + $kv = []; + foreach ($datas as $key => $value) { + $kv[] = $key."=".$value; + } + $pushLabels = []; + + $event_name = 'event_'.env('APP_ENV'); + if(!empty($labels)) $pushLabels[$event_name] = $labels; + + /* + * data format: + curl -v -H "Content-Type: application/json" -XPOST -s "http://39.96.12.39:3100/loki/api/v1/push" --data-raw \ + '{"streams": [{ "stream": { "foo": "bar2" }, "values": [ [ "1596274538882028800", "fizzbuzz" ] ] }]}' + */ + $ts = $this->getMsecTime() . '000000'; + $datas = implode("&",$kv); + $values = [[$ts,$datas]]; + $app_name = env('APP_NAME').'_'.env('APP_ENV'); + + $pushLabels['app']= $app_name; + $pushDatas = [ + 'streams'=>[ + [ + 'stream'=>$pushLabels, + 'values'=>$values, + ] + ] + ]; + $client->post( + 'http://39.96.12.39:3100/loki/api/v1/push', + [ + 'headers'=>[ + 'Content-Type'=>'application/json' + ], + 'body' => json_encode($pushDatas) + ] + ); + //var_dump(json_encode($pushDatas) ); + }); + } + + + public function push($datas){ + $this->event(null,$datas); + } + + public function getMsecTime() + { + list($msec, $sec) = explode(' ', microtime()); + $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000); + return $msectime; + } + +} diff --git a/app/Controller/AbstractController.php b/app/Controller/AbstractController.php index be3a537..b7429ea 100644 --- a/app/Controller/AbstractController.php +++ b/app/Controller/AbstractController.php @@ -15,9 +15,17 @@ use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Contract\ResponseInterface; use Psr\Container\ContainerInterface; +use App\Commons\Log; abstract class AbstractController { + + /** + * @Inject + * @var Log + */ + protected $log; + /** * @Inject * @var ContainerInterface diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index bc034d0..f69cea8 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -11,6 +11,7 @@ use Hyperf\Utils\ApplicationContext; use Hyperf\Task\TaskExecutor; use Hyperf\Task\Task; use App\TaskWorker\SSDBTask; +use App\Commons\Log; /** * @AutoController() @@ -28,14 +29,21 @@ class TestController extends AbstractController // $exec = $container->get(TaskExecutor::class); // $result = $exec->execute(new Task([MethodTask::class, 'handle'], [Coroutine::id()])); - $client = ApplicationContext::getContainer()->get(SSDBTask::class); - $result = $client->exec("set","bar","1234"); - $result = $client->exec("get","bar"); + // $client = ApplicationContext::getContainer()->get(SSDBTask::class); + // $result = $client->exec("set","bar","1234"); + // $result = $client->exec("get","bar"); // $client = ApplicationContext::getContainer()->get(MethodTask::class); // $result = $client->handle("set"); - $this->name = 'index1 action '. $result; + + //$log = ApplicationContext::getContainer()->get(Log::class); + $log = $this->log; + + $log->push(['test'=>1,'user_id'=>290,'msg'=>'order']); + $log->event('t1',['test'=>1,'user_id'=>290,'msg'=>'order']); + + //$this->name = 'index1 action '. $result; return $this->name; } diff --git a/composer.json b/composer.json index c9a89d0..3a10139 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "hyperf/config": "~2.0.0", "hyperf/db-connection": "~2.0.0", "hyperf/framework": "~2.0.0", - "hyperf/guzzle": "~2.0.0", + "hyperf/guzzle": "^2.0", "hyperf/http-server": "~2.0.0", "hyperf/logger": "~2.0.0", "hyperf/memory": "~2.0.0", @@ -31,7 +31,6 @@ "hyperf/paginator": "^2.0", "hyperf/filesystem": "^2.0", "xxtime/flysystem-aliyun-oss": "^1.5", - "hyperf/validation": "^2.0", "hyperf/task": "^2.0" }, "require-dev": { diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index e8f6126..80f707b 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -13,4 +13,5 @@ return [ \App\Service\ServiceEvaluateServiceInterface::class => \App\Service\ServiceEvaluateService::class, \App\Service\AttachmentServiceInterface::class => \App\Service\AttachmentService::class, \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, + \App\Commons\Log::class => \App\Commons\Log::class, ]; From 22cd1ea6550e6d87c4a675a9d9c192579eae50ab Mon Sep 17 00:00:00 2001 From: Mike Date: Sun, 2 Aug 2020 18:20:28 +0800 Subject: [PATCH 016/172] =?UTF-8?q?=E5=88=9B=E5=BB=BA=E6=92=AD=E6=8A=A5?= =?UTF-8?q?=E6=9C=BA=E8=B7=AF=E7=94=B1=E5=92=8Ccontroller?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/AbstractController.php | 7 ++++ app/Controller/DeviceController.php | 41 +++++++++++++++++++ app/Model/SpeakerDevic.php | 11 +++++ app/Service/DeviceServiceImp.php | 0 app/Service/DeviceServiceInterFace.php | 12 ++++++ app/TaskWorker/PubRequest.php | 56 -------------------------- config/routes.php | 8 +++- 7 files changed, 78 insertions(+), 57 deletions(-) create mode 100644 app/Controller/DeviceController.php create mode 100644 app/Model/SpeakerDevic.php create mode 100644 app/Service/DeviceServiceImp.php create mode 100644 app/Service/DeviceServiceInterFace.php delete mode 100644 app/TaskWorker/PubRequest.php diff --git a/app/Controller/AbstractController.php b/app/Controller/AbstractController.php index b7429ea..2fc26a0 100644 --- a/app/Controller/AbstractController.php +++ b/app/Controller/AbstractController.php @@ -43,4 +43,11 @@ abstract class AbstractController * @var ResponseInterface */ protected $response; + + /** + * @Inject() + * @var ValidatorFactoryInterface + */ + protected $validationFactory; + } diff --git a/app/Controller/DeviceController.php b/app/Controller/DeviceController.php new file mode 100644 index 0000000..270ac69 --- /dev/null +++ b/app/Controller/DeviceController.php @@ -0,0 +1,41 @@ +validationFactory->make( + $request->all(), + [ + 'store_id' => 'required|nonempty|integer', + ], + [ + 'store_id.required' => '参数不正确', + 'store_id.nonempty' => '参数不正确', + 'store_id.integer' => '参数不正确', + + ] + ); + + if ($validator->fails()){ + // Handle exception + $errorMessage = $validator->errors()->first(); + $this->result(200,[],$errorMessage); + } + + + + + } + + public function list() + { + + } +} \ No newline at end of file diff --git a/app/Model/SpeakerDevic.php b/app/Model/SpeakerDevic.php new file mode 100644 index 0000000..4512111 --- /dev/null +++ b/app/Model/SpeakerDevic.php @@ -0,0 +1,11 @@ +setMethod("POST"); - } - - private $topicFullName; - - private $qos; - - private $messageContent; - - private $productKey; - - public function getTopicFullName() { - return $this->topicFullName; - } - - public function setTopicFullName($topicFullName) { - $this->topicFullName = $topicFullName; - $this->queryParameters["TopicFullName"]=$topicFullName; - } - - public function getQos() { - return $this->qos; - } - - public function setQos($qos) { - $this->qos = $qos; - $this->queryParameters["Qos"]=$qos; - } - - public function getMessageContent() { - return $this->messageContent; - } - - public function setMessageContent($messageContent) { - $this->messageContent = $messageContent; - $this->queryParameters["MessageContent"]=$messageContent; - } - - public function getProductKey() { - return $this->productKey; - } - - public function setProductKey($productKey) { - $this->productKey = $productKey; - $this->queryParameters["ProductKey"]=$productKey; - } - -} \ No newline at end of file diff --git a/config/routes.php b/config/routes.php index fd08a30..0eebd7e 100644 --- a/config/routes.php +++ b/config/routes.php @@ -23,10 +23,16 @@ Router::addGroup('/v1/',function (){ Router::post('ServiceEvaluate/isPersonnel', 'App\Controller\ServiceEvaluateController@isPersonnel'); Router::post('ServiceEvaluate/getPersonnelInfo', 'App\Controller\ServiceEvaluateController@getPersonnelInfo'); Router::post('ServiceEvaluate/getEvaluateList', 'App\Controller\ServiceEvaluateController@getEvaluateList'); - Router::get('test/index1', 'App\Controller\TestController@index1'); Router::post('Attachment/uploadImage', 'App\Controller\AttachmentController@uploadImage'); Router::post('Attachment/uploadImageByBase64', 'App\Controller\AttachmentController@uploadImageByBase64'); Router::post('Attachment/upload', 'App\Controller\AttachmentController@upload'); Router::post('ParamsToken/generate', 'App\Controller\ParamsTokenController@generate'); Router::post('ParamsToken/analyze', 'App\Controller\ParamsTokenController@analyze'); + + //播报器相关 + Router::post('Device/bind', 'App\Controller\DeviceController@bind'); + Router::post('Device/list', 'App\Controller\DeviceController@list'); + + //测试路由 + Router::get('test/index1', 'App\Controller\TestController@index1'); }); \ No newline at end of file From 5d6a9aec0f89ac349ca545a95255c8b1d9eed661 Mon Sep 17 00:00:00 2001 From: Mike Date: Sun, 2 Aug 2020 19:06:21 +0800 Subject: [PATCH 017/172] =?UTF-8?q?=E5=AE=8C=E6=88=90amqp=E5=AF=B9?= =?UTF-8?q?=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 34 ++++++++++++++++++++++++ composer.json | 3 ++- config/autoload/amqp.php | 33 +++++++++++++++++++++++ 3 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 app/Amqp/Consumer/DevicOrderConsumer.php create mode 100644 config/autoload/amqp.php diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php new file mode 100644 index 0000000..ea4cc7d --- /dev/null +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -0,0 +1,34 @@ +getBody()); + if($this->msgCount< 10){ + $this->msgCount += 1; + return Result::REQUEUE; + } + return Result::ACK; + } + + public function isEnable(): bool + { + //if(env('APP_ENV')!='prod') return false; + return parent::isEnable(); + } +} diff --git a/composer.json b/composer.json index f15665e..e089108 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,8 @@ "hyperf/filesystem": "^2.0", "xxtime/flysystem-aliyun-oss": "^1.5", "hyperf/task": "^2.0", - "alibabacloud/iot": "^1.8" + "alibabacloud/iot": "^1.8", + "hyperf/amqp": "^2.0" }, "require-dev": { "swoole/ide-helper": "^4.5", diff --git a/config/autoload/amqp.php b/config/autoload/amqp.php new file mode 100644 index 0000000..e14780a --- /dev/null +++ b/config/autoload/amqp.php @@ -0,0 +1,33 @@ + [ + 'host' => env('RQM_HOST', 'localhost'), + 'port' => 5672, + 'user' => env('RQM_USER','guest'), + 'password' => env('RQM_PASSWORD','guest'), + 'vhost' => '/', + 'concurrent' => [ + 'limit' => 1, + ], + 'pool' => [ + 'min_connections' => 1, + 'max_connections' => 10, + 'connect_timeout' => 10.0, + 'wait_timeout' => 3.0, + 'heartbeat' => -1, + ], + 'params' => [ + 'insist' => false, + 'login_method' => 'AMQPLAIN', + 'login_response' => null, + 'locale' => 'en_US', + 'connection_timeout' => 3.0, + 'read_write_timeout' => 6.0, + 'context' => null, + 'keepalive' => false, + 'heartbeat' => 3, + 'close_on_destruct' => false, + ], + ] +]; From 169e37abdd15ca7ae3a73b56869da846ce8f1b72 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 3 Aug 2020 09:09:50 +0800 Subject: [PATCH 018/172] token --- app/Constants/ErrorCode.php | 5 +++ app/Controller/ParamsTokenController.php | 2 +- .../Handler/SsdbExceptionHandler.php | 37 +++++++++++++++++++ app/Exception/SsdbException.php | 18 +++++++++ app/Service/ParamsTokenSsdbService.php | 36 +++++++++++++++++- config/autoload/exceptions.php | 1 + 6 files changed, 96 insertions(+), 3 deletions(-) create mode 100644 app/Exception/Handler/SsdbExceptionHandler.php create mode 100644 app/Exception/SsdbException.php diff --git a/app/Constants/ErrorCode.php b/app/Constants/ErrorCode.php index 0651e85..229e25e 100644 --- a/app/Constants/ErrorCode.php +++ b/app/Constants/ErrorCode.php @@ -23,4 +23,9 @@ class ErrorCode extends AbstractConstants * @Message("Server Error!") */ const SERVER_ERROR = 500; + + /** + * @Message("Ssdb Error!") + */ + const SSDB_ERROR = 600; } diff --git a/app/Controller/ParamsTokenController.php b/app/Controller/ParamsTokenController.php index 0120c41..8182bbd 100644 --- a/app/Controller/ParamsTokenController.php +++ b/app/Controller/ParamsTokenController.php @@ -17,7 +17,7 @@ class ParamsTokenController extends BaseController public function generate() { $res = $this->paramsTokenService->generate($this->request->all()); - return $this->success($res); + return $this->success(['token' => $res]); } public function analyze() diff --git a/app/Exception/Handler/SsdbExceptionHandler.php b/app/Exception/Handler/SsdbExceptionHandler.php new file mode 100644 index 0000000..8eeaa0e --- /dev/null +++ b/app/Exception/Handler/SsdbExceptionHandler.php @@ -0,0 +1,37 @@ +stopPropagation(); + + $content = json_encode( + [ + "status" => 'error', + "code" => ErrorCode::SSDB_ERROR, + "result" => [], + "message" => $throwable->getMessage() ?: ErrorCode::getMessage(ErrorCode::SSDB_ERROR) + ] + ); + + return $response->withHeader('Content-Type', 'application/json') + ->withStatus($throwable->status) + ->withBody(new SwooleStream($content)); + } + + public function isValid(Throwable $throwable): bool + { + return $throwable instanceof SsdbException; + } +} \ No newline at end of file diff --git a/app/Exception/SsdbException.php b/app/Exception/SsdbException.php new file mode 100644 index 0000000..c005c38 --- /dev/null +++ b/app/Exception/SsdbException.php @@ -0,0 +1,18 @@ +get(SSDBTask::class); + + $kvs = []; + foreach ($params as $key => $value) { + $kvs[] = $key; + $kvs[] = $value; + } + + if(false === $ssdb->exec('multi_hset', self::HASH_PREFIX.$token, $kvs)) { + throw new SsdbException(ErrorCode::SSDB_ERROR, 'token生成失败'); + } + + return $token; } public function analyze($token) { - return ['page' => 'zh_cjdianc/pages/couponrebate/index', 'previous_id' => 211, 'is_expired' => 2]; + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $params = $ssdb->exec('hgetall', self::HASH_PREFIX.$token); + + if (false === $params) { + throw new SsdbException(ErrorCode::SSDB_ERROR, 'token解析失败'); + } + + if (empty($params)) { + throw new SsdbException(ErrorCode::SSDB_ERROR, 'token不存在'); + } + + return $params; } + } \ No newline at end of file diff --git a/config/autoload/exceptions.php b/config/autoload/exceptions.php index 895bda9..6417a73 100644 --- a/config/autoload/exceptions.php +++ b/config/autoload/exceptions.php @@ -14,6 +14,7 @@ return [ 'http' => [ Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class, App\Exception\Handler\AppExceptionHandler::class, + App\Exception\Handler\SsdbExceptionHandler::class, ], ], ]; From 5a9ebaa2f68beccd2cb0e6add5b2090af188fd0f Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 3 Aug 2020 10:32:30 +0800 Subject: [PATCH 019/172] =?UTF-8?q?=E5=90=88=E5=B9=B6=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E7=B1=BB=E5=88=B0=E5=BD=93=E5=89=8D=E5=88=86=E6=94=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Commons/Log.php | 88 +++++++++++++++++++++++++++ app/Controller/AbstractController.php | 8 +++ app/Controller/TestController.php | 16 +++-- composer.json | 2 +- config/autoload/dependencies.php | 4 ++ 5 files changed, 113 insertions(+), 5 deletions(-) create mode 100644 app/Commons/Log.php diff --git a/app/Commons/Log.php b/app/Commons/Log.php new file mode 100644 index 0000000..bf5fb24 --- /dev/null +++ b/app/Commons/Log.php @@ -0,0 +1,88 @@ +clientFactory = $clientFactory; + } + + public function getClient() + { + // $options 等同于 GuzzleHttp\Client 构造函数的 $config 参数 + $options = [ + 'timeout' => 2.0, + ]; + // $client 为协程化的 GuzzleHttp\Client 对象 + $client = $this->clientFactory->create($options); + + return $client; + } + + public function event($labels=null,$datas){ + + co(function () use ($labels,$datas){ + + $client = $this->getClient(); + $kv = []; + foreach ($datas as $key => $value) { + $kv[] = $key."=".$value; + } + $pushLabels = []; + + $event_name = 'event_'.env('APP_ENV'); + if(!empty($labels)) $pushLabels[$event_name] = $labels; + + /* + * data format: + curl -v -H "Content-Type: application/json" -XPOST -s "http://39.96.12.39:3100/loki/api/v1/push" --data-raw \ + '{"streams": [{ "stream": { "foo": "bar2" }, "values": [ [ "1596274538882028800", "fizzbuzz" ] ] }]}' + */ + $ts = $this->getMsecTime() . '000000'; + $datas = implode("&",$kv); + $values = [[$ts,$datas]]; + $app_name = env('APP_NAME').'_'.env('APP_ENV'); + + $pushLabels['app']= $app_name; + $pushDatas = [ + 'streams'=>[ + [ + 'stream'=>$pushLabels, + 'values'=>$values, + ] + ] + ]; + $client->post( + 'http://39.96.12.39:3100/loki/api/v1/push', + [ + 'headers'=>[ + 'Content-Type'=>'application/json' + ], + 'body' => json_encode($pushDatas) + ] + ); + //var_dump(json_encode($pushDatas) ); + }); + } + + + public function push($datas){ + $this->event(null,$datas); + } + + public function getMsecTime() + { + list($msec, $sec) = explode(' ', microtime()); + $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000); + return $msectime; + } + +} diff --git a/app/Controller/AbstractController.php b/app/Controller/AbstractController.php index be3a537..b7429ea 100644 --- a/app/Controller/AbstractController.php +++ b/app/Controller/AbstractController.php @@ -15,9 +15,17 @@ use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Contract\ResponseInterface; use Psr\Container\ContainerInterface; +use App\Commons\Log; abstract class AbstractController { + + /** + * @Inject + * @var Log + */ + protected $log; + /** * @Inject * @var ContainerInterface diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index bc034d0..f69cea8 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -11,6 +11,7 @@ use Hyperf\Utils\ApplicationContext; use Hyperf\Task\TaskExecutor; use Hyperf\Task\Task; use App\TaskWorker\SSDBTask; +use App\Commons\Log; /** * @AutoController() @@ -28,14 +29,21 @@ class TestController extends AbstractController // $exec = $container->get(TaskExecutor::class); // $result = $exec->execute(new Task([MethodTask::class, 'handle'], [Coroutine::id()])); - $client = ApplicationContext::getContainer()->get(SSDBTask::class); - $result = $client->exec("set","bar","1234"); - $result = $client->exec("get","bar"); + // $client = ApplicationContext::getContainer()->get(SSDBTask::class); + // $result = $client->exec("set","bar","1234"); + // $result = $client->exec("get","bar"); // $client = ApplicationContext::getContainer()->get(MethodTask::class); // $result = $client->handle("set"); - $this->name = 'index1 action '. $result; + + //$log = ApplicationContext::getContainer()->get(Log::class); + $log = $this->log; + + $log->push(['test'=>1,'user_id'=>290,'msg'=>'order']); + $log->event('t1',['test'=>1,'user_id'=>290,'msg'=>'order']); + + //$this->name = 'index1 action '. $result; return $this->name; } diff --git a/composer.json b/composer.json index 3b9ff4f..3d44a8c 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "hyperf/config": "~2.0.0", "hyperf/db-connection": "~2.0.0", "hyperf/framework": "~2.0.0", - "hyperf/guzzle": "~2.0.0", + "hyperf/guzzle": "^2.0", "hyperf/http-server": "~2.0.0", "hyperf/logger": "~2.0.0", "hyperf/memory": "~2.0.0", diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 9096061..547a711 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -10,5 +10,9 @@ declare(strict_types=1); * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ return [ + \App\Service\ServiceEvaluateServiceInterface::class => \App\Service\ServiceEvaluateService::class, + \App\Service\AttachmentServiceInterface::class => \App\Service\AttachmentService::class, + \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class + \App\Commons\Log::class => \App\Commons\Log::class, ]; From 1555fe2a07fd64f84f7fd498b0e55518d2306c9d Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 3 Aug 2020 10:48:41 +0800 Subject: [PATCH 020/172] =?UTF-8?q?=E5=A4=84=E7=90=86=E5=90=88=E5=B9=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/autoload/dependencies.php | 1 - 1 file changed, 1 deletion(-) diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 547a711..80f707b 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -13,6 +13,5 @@ return [ \App\Service\ServiceEvaluateServiceInterface::class => \App\Service\ServiceEvaluateService::class, \App\Service\AttachmentServiceInterface::class => \App\Service\AttachmentService::class, \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, - \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class \App\Commons\Log::class => \App\Commons\Log::class, ]; From f8f90aa0bf6f8cf9e96b517fd98e91d7242cb4a3 Mon Sep 17 00:00:00 2001 From: Mike Date: Mon, 3 Aug 2020 16:04:21 +0800 Subject: [PATCH 021/172] =?UTF-8?q?=E7=BB=91=E5=AE=9A=E5=92=8Cservice?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/AbstractController.php | 3 ++- app/Controller/DeviceController.php | 26 +++++++++++++++++++---- app/Service/DeviceServiceImp.php | 29 ++++++++++++++++++++++++++ app/Service/DeviceServiceInterFace.php | 2 -- config/autoload/dependencies.php | 1 + 5 files changed, 54 insertions(+), 7 deletions(-) diff --git a/app/Controller/AbstractController.php b/app/Controller/AbstractController.php index 2fc26a0..30df791 100644 --- a/app/Controller/AbstractController.php +++ b/app/Controller/AbstractController.php @@ -15,6 +15,7 @@ use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Contract\ResponseInterface; use Psr\Container\ContainerInterface; +use Hyperf\Validation\Contract\ValidatorFactoryInterface; use App\Commons\Log; abstract class AbstractController @@ -45,7 +46,7 @@ abstract class AbstractController protected $response; /** - * @Inject() + * @Inject * @var ValidatorFactoryInterface */ protected $validationFactory; diff --git a/app/Controller/DeviceController.php b/app/Controller/DeviceController.php index 270ac69..438a651 100644 --- a/app/Controller/DeviceController.php +++ b/app/Controller/DeviceController.php @@ -5,21 +5,34 @@ namespace App\Controller; use Hyperf\Di\Annotation\Inject; use App\Constants\ErrorCode; use App\Exception\BusinessException; +use App\Service\DeviceServiceInterFace; class DeviceController extends BaseController { + + /** + * @Inject + * @var DeviceServiceInterFace + */ + protected $deviceService; + + public function bind() { $validator = $this->validationFactory->make( - $request->all(), + $this->request->all(), [ 'store_id' => 'required|nonempty|integer', + 'device_name' => 'required|nonempty|alpha_num', + ], [ 'store_id.required' => '参数不正确', 'store_id.nonempty' => '参数不正确', 'store_id.integer' => '参数不正确', - + 'device_name.required' => '参数不正确', + 'device_name.nonempty' => '参数不正确', + 'device_name.alpha_num' => '参数不正确', ] ); @@ -29,9 +42,14 @@ class DeviceController extends BaseController $this->result(200,[],$errorMessage); } - - + $store_id = $this->request->input('store_id'); + $device_name = $this->request->input('device_name'); + + $sd = $this->deviceService->bindByStoreId($device_name,$store_id); + + return $this->result(0,[$sd],'绑定成功'); + } public function list() diff --git a/app/Service/DeviceServiceImp.php b/app/Service/DeviceServiceImp.php index e69de29..b022683 100644 --- a/app/Service/DeviceServiceImp.php +++ b/app/Service/DeviceServiceImp.php @@ -0,0 +1,29 @@ +store_id = $store_id; + $sd->device_name = $dev_name; + $sd->market_id = 1; + $sd->bind_time = time(); + $sd->saveOrFail(); + }catch(Exception $e){ + //var_dump($e); + } + return $sd; + } + public function pubMsgByStoreIdAndDevName($dev_name,$store_id,$msg){ + + } +} \ No newline at end of file diff --git a/app/Service/DeviceServiceInterFace.php b/app/Service/DeviceServiceInterFace.php index 388583f..e22e184 100644 --- a/app/Service/DeviceServiceInterFace.php +++ b/app/Service/DeviceServiceInterFace.php @@ -1,9 +1,7 @@ \App\Service\ServiceEvaluateService::class, \App\Service\AttachmentServiceInterface::class => \App\Service\AttachmentService::class, \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, + \App\Service\DeviceServiceInterFace::class =>\App\Service\DeviceServiceImp::class, \App\Commons\Log::class => \App\Commons\Log::class, ]; From 6ab5eff503ebe101a9901737eddc65e6278185a0 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Mon, 3 Aug 2020 17:00:37 +0800 Subject: [PATCH 022/172] =?UTF-8?q?=E8=BF=94=E5=88=B8=E6=8E=A5=E5=8F=A3=20?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 16 ++++++++++------ app/CouponRebate/CouponRebate.php | 19 +++++++++++++++++++ app/CouponRebate/CouponRebateInterface.php | 10 ++++++++++ config/autoload/dependencies.php | 1 + config/routes.php | 1 + 5 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 app/CouponRebate/CouponRebate.php create mode 100644 app/CouponRebate/CouponRebateInterface.php diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 7ed921d..3d344cb 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -11,18 +11,22 @@ declare(strict_types=1); */ namespace App\Controller; - -use App\Model\CouponUserRecType; -use App\Model\Coupon; -use App\Model\CouponRec; use Hyperf\DbConnection\Db; use Hyperf\Redis\Redis; use Hyperf\Utils\ApplicationContext; - +use App\CouponRebate\CouponRebateInterface; +use http\Client\Curl\User; +use Hyperf\Di\Annotation\Inject; class CouponRebateController extends BaseController { + /** + * @Inject + * @var CouponRebateInterface + */ + protected $CouponRebate; public function isCouponRebate() { - return $this->success('创建成功'); + $res = $this->CouponRebate->isCouponRebate('测试数据'); + return $this->success($res); } } diff --git a/app/CouponRebate/CouponRebate.php b/app/CouponRebate/CouponRebate.php new file mode 100644 index 0000000..d006177 --- /dev/null +++ b/app/CouponRebate/CouponRebate.php @@ -0,0 +1,19 @@ + \App\Service\AttachmentService::class, \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, \App\Commons\Log::class => \App\Commons\Log::class, + \App\CouponRebate\CouponRebateInterface::class => \App\CouponRebate\CouponRebate::class, ]; diff --git a/config/routes.php b/config/routes.php index 88b8a99..7305ea3 100644 --- a/config/routes.php +++ b/config/routes.php @@ -25,4 +25,5 @@ Router::addGroup('/v1/',function (){ Router::get('test/index1', 'App\Controller\TestController@index1'); Router::post('ParamsToken/generate', 'App\Controller\ParamsTokenController@generate'); Router::post('ParamsToken/analyze', 'App\Controller\ParamsTokenController@analyze'); + Router::post('CouponRebate/isCouponRebate', 'App\Controller\CouponRebateController@isCouponRebate'); }); \ No newline at end of file From 96cc3ef11a5408d1c36ff4be83268e33c7a07e19 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 3 Aug 2020 17:31:16 +0800 Subject: [PATCH 023/172] =?UTF-8?q?=E5=88=86=E4=BA=AB=E9=A1=B5token?= =?UTF-8?q?=E3=80=81=E9=A6=96=E9=A1=B5banner?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/ErrorCode.php | 5 + app/Constants/LogLabel.php | 19 +++ app/Constants/SsdbKeysPrefix.php | 19 +++ app/Controller/AdController.php | 27 +++++ app/Controller/ParamsTokenController.php | 22 +++- .../Handler/SsdbExceptionHandler.php | 14 +-- .../Handler/ValidationExceptionHandler.php | 35 ++++++ .../ValidatorFactoryResolvedListener.php | 113 ++++++++++++++++++ app/Model/Ad.php | 70 +++++++++++ app/Service/AdService.php | 20 ++++ app/Service/AdServiceInterface.php | 11 ++ app/Service/ParamsTokenServiceInterface.php | 13 +- app/Service/ParamsTokenSsdbService.php | 41 ++++++- config/autoload/dependencies.php | 1 + config/autoload/exceptions.php | 1 + config/autoload/listeners.php | 1 + config/autoload/middlewares.php | 1 + config/routes.php | 1 + 18 files changed, 395 insertions(+), 19 deletions(-) create mode 100644 app/Constants/LogLabel.php create mode 100644 app/Constants/SsdbKeysPrefix.php create mode 100644 app/Controller/AdController.php create mode 100644 app/Exception/Handler/ValidationExceptionHandler.php create mode 100644 app/Listener/ValidatorFactoryResolvedListener.php create mode 100644 app/Model/Ad.php create mode 100644 app/Service/AdService.php create mode 100644 app/Service/AdServiceInterface.php diff --git a/app/Constants/ErrorCode.php b/app/Constants/ErrorCode.php index 229e25e..506e36c 100644 --- a/app/Constants/ErrorCode.php +++ b/app/Constants/ErrorCode.php @@ -24,6 +24,11 @@ class ErrorCode extends AbstractConstants */ const SERVER_ERROR = 500; + /** + * @Message("Params Invalid!") + */ + const PARAMS_INVALID = 900; + /** * @Message("Ssdb Error!") */ diff --git a/app/Constants/LogLabel.php b/app/Constants/LogLabel.php new file mode 100644 index 0000000..2265cf4 --- /dev/null +++ b/app/Constants/LogLabel.php @@ -0,0 +1,19 @@ +success($this->adService->banners()); + } +} diff --git a/app/Controller/ParamsTokenController.php b/app/Controller/ParamsTokenController.php index 8182bbd..db1cdca 100644 --- a/app/Controller/ParamsTokenController.php +++ b/app/Controller/ParamsTokenController.php @@ -1,11 +1,15 @@ paramsTokenService->generate($this->request->all()); - return $this->success(['token' => $res]); + $token = $this->paramsTokenService->generate($this->request->all()); + return $this->success(['token' => $token]); } + /** + * 解析token获取对应参数数据 + * @return \Psr\Http\Message\ResponseInterface + */ public function analyze() { - $res = $this->paramsTokenService->analyze($this->request->input('token')); - return $this->success($res); + $params = $this->paramsTokenService->analyze($this->request->input('token')); + return $this->success($params); } } \ No newline at end of file diff --git a/app/Exception/Handler/SsdbExceptionHandler.php b/app/Exception/Handler/SsdbExceptionHandler.php index 8eeaa0e..118d5ef 100644 --- a/app/Exception/Handler/SsdbExceptionHandler.php +++ b/app/Exception/Handler/SsdbExceptionHandler.php @@ -16,18 +16,14 @@ class SsdbExceptionHandler extends ExceptionHandler { $this->stopPropagation(); - $content = json_encode( - [ + $content = json_encode([ "status" => 'error', - "code" => ErrorCode::SSDB_ERROR, + "code" => $throwable->getCode(), "result" => [], - "message" => $throwable->getMessage() ?: ErrorCode::getMessage(ErrorCode::SSDB_ERROR) - ] - ); + "message" => $throwable->getMessage() + ]); - return $response->withHeader('Content-Type', 'application/json') - ->withStatus($throwable->status) - ->withBody(new SwooleStream($content)); + return $response->withHeader('Content-Type', 'application/json')->withBody(new SwooleStream($content)); } public function isValid(Throwable $throwable): bool diff --git a/app/Exception/Handler/ValidationExceptionHandler.php b/app/Exception/Handler/ValidationExceptionHandler.php new file mode 100644 index 0000000..cc2384c --- /dev/null +++ b/app/Exception/Handler/ValidationExceptionHandler.php @@ -0,0 +1,35 @@ +stopPropagation(); + + $content = json_encode([ + "status" => 'error', + "code" => ErrorCode::PARAMS_INVALID, + "result" => [], + "message" => $throwable->validator->errors()->first() + ]); + + return $response->withHeader('Content-Type', 'application/json') + ->withStatus($throwable->status) + ->withBody(new SwooleStream($content)); + } + + public function isValid(Throwable $throwable): bool + { + return $throwable instanceof ValidationException; + } +} \ No newline at end of file diff --git a/app/Listener/ValidatorFactoryResolvedListener.php b/app/Listener/ValidatorFactoryResolvedListener.php new file mode 100644 index 0000000..75b3a36 --- /dev/null +++ b/app/Listener/ValidatorFactoryResolvedListener.php @@ -0,0 +1,113 @@ +validatorFactory; + + // 注册了 nonempty 验证器规则 + $validatorFactory->extend('nonempty', function ($attribute, $value, $parameters, $validator) { + + return isset($value) + && $value + && !empty($value) + && !is_null($value) + && $value != 'undefined' + && $value != 'unknown' + && $value != 'null' + && $value != 'false'; + + }); + + // 注册了 strlen 验证器规则,参数是min,max,最小长度和最大长度 + $validatorFactory->extend('strlen', function ($attribute, $value, $parameters, $validator) { + return mb_strlen($value)>=$parameters[0] && mb_strlen($value)<=$parameters[1]; + }); + $validatorFactory->replacer('strlen', function ($message, $attribute, $rule, $parameters) { + $message = str_replace(':min', $parameters[0], $message); + $message = str_replace(':max', $parameters[1], $message); + return $message; + }); + + // 注册了 base64 验证器规则 + $validatorFactory->extend('base64', function ($attribute, $value, $parameters, $validator) { + + preg_match('/^(data:\s*image\/(\w+);base64,)/', $value, $result); + + if (empty($result)) { + return false; + } + + if ( + in_array('image', $parameters) + && !in_array($result[2], ['jpg','jpeg','png','gif','svg','bmp']) + ) { + return false; + } + + return true; + + }); + + // 注册了 ext_not_in 验证器规则 + $validatorFactory->extend('ext_not_in', function ($attribute, $value, $parameters, $validator) { + + if (empty($parameters)) { + $parameters = ['', 'php', 'exe', 'sql', 'sh', 'bat', 'py', 'go', 'c', 'cpp']; + } + return !in_array($value->getExtension(), $parameters); + + }); + + // 注册了 exists_enable 验证器规则,参数是table,field,where1,where2... + $validatorFactory->extend('exists_enable', function ($attribute, $value, $parameters, $validator) { + + // 查询 + $builder = Db::table($parameters[0])->where($parameters[1], '=', $value); + + $whereArr = array_slice($parameters,2); + if (!empty($whereArr)) { + foreach ($whereArr as $key => $where) { + $builder->whereRaw($where); + } + } + + return $builder->exists(); + }); + + // 注册了 not_equal 验证器规则,参数是anotherfield,table,primary_field,foreign_field + // 要排除对比的字段请求参数名、表名、本参数对应表id、比较字段 + $validatorFactory->extend('not_equal', function ($attribute, $value, $parameters, $validator) { + + // 获取比较字段参数值 + $foreignValue = $validator->getData()[$parameters[0]]; + + // 查询 + $builder = Db::table($parameters[1]) + ->where($parameters[2], '=', $value) + ->where($parameters[3], '!=', $foreignValue) + ; + + return $builder->exists(); + }); + } +} \ No newline at end of file diff --git a/app/Model/Ad.php b/app/Model/Ad.php new file mode 100644 index 0000000..71cdbf9 --- /dev/null +++ b/app/Model/Ad.php @@ -0,0 +1,70 @@ + 'page', + 2 => 'webview', + 3 => 'applet', + ]; + + /** + * 类型 1 = 首页banners + */ + const TYPE_BANNER = 1; + + /** + * 启用状态 + */ + const STATUS_YES = 1; + const STATUS_NO = 2; + + /** + * The table associated with the model. + * + * @var string + */ + protected $table = 'ims_cjdc_ad'; + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = []; + /** + * The attributes that should be cast to native types. + * + * @var array + */ + protected $casts = []; + + protected $appends = [ + 'item_text', + 'redirect_url' + ]; + + /** + * 获取跳转说明 + */ + public function getItemTextAttribute() + { + return self::ITEM[$this->item]; + } + + /** + * 获取跳转连接 + */ + public function getRedirectUrlAttribute() + { + return $this->src ?: $this->src2; + } +} \ No newline at end of file diff --git a/app/Service/AdService.php b/app/Service/AdService.php new file mode 100644 index 0000000..77170ac --- /dev/null +++ b/app/Service/AdService.php @@ -0,0 +1,20 @@ +select(['id','title','logo','item','src','src2']) + ->where([ + 'type' => Ad::TYPE_BANNER, + 'status' => Ad::STATUS_YES + ])->get(); + } +} \ No newline at end of file diff --git a/app/Service/AdServiceInterface.php b/app/Service/AdServiceInterface.php new file mode 100644 index 0000000..f488422 --- /dev/null +++ b/app/Service/AdServiceInterface.php @@ -0,0 +1,11 @@ +exec('multi_hset', self::HASH_PREFIX.$token, $kvs)) { + if(false === $ssdb->exec('multi_hset', SsdbKeysPrefix::PARAMS_TOKEN.$token, $kvs)) { + + $this->log->event( + LogLabel::SSDB_LOG, + ['method' => 'multi_hset', 'key' => SsdbKeysPrefix::PARAMS_TOKEN.$token, 'kvs' => $kvs] + ); + throw new SsdbException(ErrorCode::SSDB_ERROR, 'token生成失败'); } return $token; } + /** + * 解析token获取对应数据参数 + * @param $token + */ public function analyze($token) { $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - $params = $ssdb->exec('hgetall', self::HASH_PREFIX.$token); + $params = $ssdb->exec('hgetall', SsdbKeysPrefix::PARAMS_TOKEN.$token); if (false === $params) { + + $this->log->event( + LogLabel::SSDB_LOG, + ['method' => 'hgetall', 'key' => SsdbKeysPrefix::PARAMS_TOKEN.$token, 'params' => $params] + ); + throw new SsdbException(ErrorCode::SSDB_ERROR, 'token解析失败'); } if (empty($params)) { + + $this->log->event( + LogLabel::SSDB_LOG, + ['method' => 'hgetall', 'key' => SsdbKeysPrefix::PARAMS_TOKEN.$token, 'params' => $params] + ); + throw new SsdbException(ErrorCode::SSDB_ERROR, 'token不存在'); } diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 80f707b..74f9420 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -13,5 +13,6 @@ return [ \App\Service\ServiceEvaluateServiceInterface::class => \App\Service\ServiceEvaluateService::class, \App\Service\AttachmentServiceInterface::class => \App\Service\AttachmentService::class, \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, + \App\Service\AdServiceInterface::class => \App\Service\AdService::class, \App\Commons\Log::class => \App\Commons\Log::class, ]; diff --git a/config/autoload/exceptions.php b/config/autoload/exceptions.php index 6417a73..0aa0812 100644 --- a/config/autoload/exceptions.php +++ b/config/autoload/exceptions.php @@ -14,6 +14,7 @@ return [ 'http' => [ Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class, App\Exception\Handler\AppExceptionHandler::class, + App\Exception\Handler\ValidationExceptionHandler::class, App\Exception\Handler\SsdbExceptionHandler::class, ], ], diff --git a/config/autoload/listeners.php b/config/autoload/listeners.php index 55b80d5..2741751 100644 --- a/config/autoload/listeners.php +++ b/config/autoload/listeners.php @@ -10,4 +10,5 @@ declare(strict_types=1); * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ return [ + \App\Listener\ValidatorFactoryResolvedListener::class, ]; diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index 292a74a..5eb19a5 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -12,6 +12,7 @@ declare(strict_types=1); return [ 'http' => [ \App\Middleware\Auth\ApiMiddleware::class, + \Hyperf\Validation\Middleware\ValidationMiddleware::class, \App\Middleware\CorsMiddleware::class, ], ]; diff --git a/config/routes.php b/config/routes.php index 88b8a99..97cea66 100644 --- a/config/routes.php +++ b/config/routes.php @@ -25,4 +25,5 @@ Router::addGroup('/v1/',function (){ Router::get('test/index1', 'App\Controller\TestController@index1'); Router::post('ParamsToken/generate', 'App\Controller\ParamsTokenController@generate'); Router::post('ParamsToken/analyze', 'App\Controller\ParamsTokenController@analyze'); + Router::post('Ad/banners', 'App\Controller\AdController@banners'); }); \ No newline at end of file From dbe2c06e9764f96ed845c4962723ce19b1d0aca8 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Mon, 3 Aug 2020 17:48:06 +0800 Subject: [PATCH 024/172] =?UTF-8?q?=E5=88=A4=E6=96=AD=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E9=A2=86=E8=BF=87=E5=88=86=E4=BA=AB=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E4=BC=98=E6=83=A0=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 3 ++- app/CouponRebate/CouponRebate.php | 13 ++++++++++--- app/CouponRebate/CouponRebateInterface.php | 2 +- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 3d344cb..3f90802 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -26,7 +26,8 @@ class CouponRebateController extends BaseController protected $CouponRebate; public function isCouponRebate() { - $res = $this->CouponRebate->isCouponRebate('测试数据'); + $user_id = $this->request->input('user_id', 0); + $res = $this->CouponRebate->isCouponRebate($user_id); return $this->success($res); } } diff --git a/app/CouponRebate/CouponRebate.php b/app/CouponRebate/CouponRebate.php index d006177..88f8d7f 100644 --- a/app/CouponRebate/CouponRebate.php +++ b/app/CouponRebate/CouponRebate.php @@ -10,10 +10,17 @@ use Hyperf\Paginator\Paginator; class CouponRebate implements CouponRebateInterface { - public function isCouponRebate($data) + public function isCouponRebate($user_id) { - // 当前用户是否今日新注册并第一次提交评论 - return $data; + $res = Db::table('ims_system_coupon_user as u') + ->join('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id') + ->where([ + ['r.user_id','=',$user_id], + ['u.active_type','=',2] + ]) + ->select('r.id') + ->first(); + return $res; } } \ No newline at end of file diff --git a/app/CouponRebate/CouponRebateInterface.php b/app/CouponRebate/CouponRebateInterface.php index 8f18adb..8c63313 100644 --- a/app/CouponRebate/CouponRebateInterface.php +++ b/app/CouponRebate/CouponRebateInterface.php @@ -5,6 +5,6 @@ namespace App\CouponRebate; interface CouponRebateInterface { - public function isCouponRebate($data); + public function isCouponRebate($user_id); } \ No newline at end of file From f6eb266a86d1c0e1eb9bd20047386624b9ba9f5f Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 4 Aug 2020 11:56:57 +0800 Subject: [PATCH 025/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8--=E6=B7=BB=E5=8A=A0=E9=A2=86=E5=8F=96=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponController.php | 1 + app/Controller/CouponRebateController.php | 91 ++++++++++++++++++++++ app/Request/couponRebateReceiveRequest.php | 48 ++++++++++++ 3 files changed, 140 insertions(+) create mode 100644 app/Request/couponRebateReceiveRequest.php diff --git a/app/Controller/CouponController.php b/app/Controller/CouponController.php index 409c2cf..5152e63 100644 --- a/app/Controller/CouponController.php +++ b/app/Controller/CouponController.php @@ -67,6 +67,7 @@ class CouponController extends BaseController ['u.end_time','>',$nowTime], ['u.start_time','<=',$nowTime], ['u.status','=',1], + ['u.active_type','=',1], ]; if (env('SUB_CHANNEL') == 1) { diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 3f90802..12696a6 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -17,6 +17,10 @@ use Hyperf\Utils\ApplicationContext; use App\CouponRebate\CouponRebateInterface; use http\Client\Curl\User; use Hyperf\Di\Annotation\Inject; +use App\Model\Coupon; +use App\Model\CouponUserRecType; +use App\Model\CouponRec; +use App\Request\CouponRebateReceiveRequest; class CouponRebateController extends BaseController { /** @@ -30,4 +34,91 @@ class CouponRebateController extends BaseController $res = $this->CouponRebate->isCouponRebate($user_id); return $this->success($res); } + + /** + * 用户领取优惠券 + */ + public function userReceiveCouponA(couponRebateReceiveRequest $validator) + { + $userId = $this->request->input("user_id", 0); + $receiveType = $this->request->input("receive_type", 0); + $ids = $this->request->input("ids", ''); + $sendUserId = $this->request->input("send_user_id", 0); + $phone = $this->request->input("phone", ''); + $ids = explode(',', $ids); + $now = time(); + + // moke 数据 给前端用 + $test = $this->request->input("test", 0); + if($test){ + $cps = Coupon::whereIn('id', $ids)->lockForUpdate()->first(); + return $this->success([ + 'success' => [$cps], + 'fail' => [], + ]); + } + + $success = []; + $fail = []; + + Db::transaction( function () use ($ids,$receiveType,$userId,$sendUserId,$phone,&$success,&$fail,$now) { + //读写锁,完全控制,性能低 + $cps = Coupon::whereIn('id', $ids)->lockForUpdate() + ->select('id','title','status','inventory','inventory_use','start_time','end_time') + ->get(); + + foreach ($cps as $key => $cp) { + + $where = [ + 'system_coupon_user_id' => $cp->id, + ]; + + if (env('SUB_CHANNEL') == 1) { + $where['receive_type'] = $receiveType; + } + + $crt = CouponUserRecType::where($where)->first(); + + $cr = new CouponRec; + $cr->user_id = $userId; + $cr->system_coupon_user_id = $cp->id; + $cr->order_main_id = 0; + $cr->receive_time = $now; + $cr->number = $crt->one_receive_number; + $cr->number_remain = $crt->one_receive_number; + $cr->status = 0; + $cr->update_time = $now; + $cr->receive_type = $receiveType; + $cr->send_user_id = $sendUserId; + $cr->phone = $phone; + //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内, 则返回领取失败的优惠券 + if ( + $cp->status != 1 + || + $cp->inventory <= $cp->inventory_use + || + $cp->inventory < ($cp->inventory_use+$cr->number) + || + $cp->start_time < $now + || + $cp->end_time > $now + ) + { + $fail[] = $cp; + }else{ + $cp->inventory_use += $cr->number;//记录已领取的数量 + if ( $cr->save() && $cp->save() ) { + $success[] = $cp; + } else { + $fail[] = $cp; + } + } + } + }); + + return $this->success([ + 'success' => $success, + 'fail' => $fail, + ]); + } } diff --git a/app/Request/couponRebateReceiveRequest.php b/app/Request/couponRebateReceiveRequest.php new file mode 100644 index 0000000..4c4beed --- /dev/null +++ b/app/Request/couponRebateReceiveRequest.php @@ -0,0 +1,48 @@ + 'required|nonempty|integer|exists_enable:ims_cjdc_user,id', + 'receive_type' => 'required|nonempty|integer', + 'ids' => 'required|nonempty', + ]; + } + + public function messages(): array + { + return [ + 'user_id.*' => ':attribute信息不正确', + 'receive_type.*' => ':attribute必须', + 'ids.*' => ':attribute必须', + ]; + } + + public function attributes(): array + { + return [ + 'user_id' => '领取用户ID', + 'receive_type' => '领取方式', + 'ids' => '优惠券', + ]; + } +} From ccfac7644e9dbe1c3308b11404dcae56eff141a4 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 4 Aug 2020 15:30:26 +0800 Subject: [PATCH 026/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8--=E7=BB=99=E5=89=8D=E7=AB=AFmock=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=EF=BC=8C=E6=B7=BB=E5=8A=A0=E8=B7=AF=E7=94=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 6 ++++-- config/routes.php | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 12696a6..150e7fa 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -48,10 +48,12 @@ class CouponRebateController extends BaseController $ids = explode(',', $ids); $now = time(); - // moke 数据 给前端用 + // mock 数据 给前端用 $test = $this->request->input("test", 0); if($test){ - $cps = Coupon::whereIn('id', $ids)->lockForUpdate()->first(); + $cps = Coupon::whereIn('id', $ids)->lockForUpdate() + ->select('id','title','status','inventory','inventory_use','start_time','end_time') + ->first(); return $this->success([ 'success' => [$cps], 'fail' => [], diff --git a/config/routes.php b/config/routes.php index 83a8e13..0b238a6 100644 --- a/config/routes.php +++ b/config/routes.php @@ -26,5 +26,6 @@ Router::addGroup('/v1/',function (){ Router::post('ParamsToken/generate', 'App\Controller\ParamsTokenController@generate'); Router::post('ParamsToken/analyze', 'App\Controller\ParamsTokenController@analyze'); Router::post('Ad/banners', 'App\Controller\AdController@banners'); - Router::post('CouponRebate/isCouponRebate', 'App\Controller\CouponRebateController@isCouponRebate'); + Router::post('CouponRebate/isCouponRebate', 'App\Controller\CouponRebateController@isCouponRebate'); + Router::post('CouponRebate/userReceiveCoupon', 'App\Controller\CouponRebateController@userReceiveCouponA'); }); \ No newline at end of file From 425a2d810e538d1e7f0a5dffbba554000e7d6790 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 4 Aug 2020 16:35:33 +0800 Subject: [PATCH 027/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8--=E4=BF=AE=E6=94=B9=E9=AA=8C=E8=AF=81=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 2 +- app/Request/couponRebateReceiveRequest.php | 48 ---------------------- 2 files changed, 1 insertion(+), 49 deletions(-) delete mode 100644 app/Request/couponRebateReceiveRequest.php diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 150e7fa..89e1cd3 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -38,7 +38,7 @@ class CouponRebateController extends BaseController /** * 用户领取优惠券 */ - public function userReceiveCouponA(couponRebateReceiveRequest $validator) + public function userReceiveCouponA(CouponRebateReceiveRequest $validator) { $userId = $this->request->input("user_id", 0); $receiveType = $this->request->input("receive_type", 0); diff --git a/app/Request/couponRebateReceiveRequest.php b/app/Request/couponRebateReceiveRequest.php deleted file mode 100644 index 4c4beed..0000000 --- a/app/Request/couponRebateReceiveRequest.php +++ /dev/null @@ -1,48 +0,0 @@ - 'required|nonempty|integer|exists_enable:ims_cjdc_user,id', - 'receive_type' => 'required|nonempty|integer', - 'ids' => 'required|nonempty', - ]; - } - - public function messages(): array - { - return [ - 'user_id.*' => ':attribute信息不正确', - 'receive_type.*' => ':attribute必须', - 'ids.*' => ':attribute必须', - ]; - } - - public function attributes(): array - { - return [ - 'user_id' => '领取用户ID', - 'receive_type' => '领取方式', - 'ids' => '优惠券', - ]; - } -} From 0c6f0dbd52f261814001cb6deedf4665423511f4 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 4 Aug 2020 16:49:27 +0800 Subject: [PATCH 028/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8--=E9=A2=86=E5=8F=96=E4=BC=98=E6=83=A0=E5=88=B8?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E5=8A=A0=E9=AA=8C=E8=AF=81=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Request/CouponRebateReceiveRequest.php | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 app/Request/CouponRebateReceiveRequest.php diff --git a/app/Request/CouponRebateReceiveRequest.php b/app/Request/CouponRebateReceiveRequest.php new file mode 100644 index 0000000..4c4beed --- /dev/null +++ b/app/Request/CouponRebateReceiveRequest.php @@ -0,0 +1,48 @@ + 'required|nonempty|integer|exists_enable:ims_cjdc_user,id', + 'receive_type' => 'required|nonempty|integer', + 'ids' => 'required|nonempty', + ]; + } + + public function messages(): array + { + return [ + 'user_id.*' => ':attribute信息不正确', + 'receive_type.*' => ':attribute必须', + 'ids.*' => ':attribute必须', + ]; + } + + public function attributes(): array + { + return [ + 'user_id' => '领取用户ID', + 'receive_type' => '领取方式', + 'ids' => '优惠券', + ]; + } +} From ebedccb17282486666b4b05ec9f0485bd7dca3d9 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 4 Aug 2020 16:52:30 +0800 Subject: [PATCH 029/172] =?UTF-8?q?=E9=A2=86=E5=88=B8=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/CouponRebate/CouponRebate.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/CouponRebate/CouponRebate.php b/app/CouponRebate/CouponRebate.php index 88f8d7f..f687113 100644 --- a/app/CouponRebate/CouponRebate.php +++ b/app/CouponRebate/CouponRebate.php @@ -13,7 +13,7 @@ class CouponRebate implements CouponRebateInterface public function isCouponRebate($user_id) { $res = Db::table('ims_system_coupon_user as u') - ->join('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id') + ->leftjoin('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id') ->where([ ['r.user_id','=',$user_id], ['u.active_type','=',2] From 33ce9d99e136b4104daf32ec889512ef6ef66679 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 4 Aug 2020 17:14:35 +0800 Subject: [PATCH 030/172] =?UTF-8?q?=E9=A2=86=E5=88=B8=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/CouponRebate/CouponRebate.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/CouponRebate/CouponRebate.php b/app/CouponRebate/CouponRebate.php index f687113..85cf4e5 100644 --- a/app/CouponRebate/CouponRebate.php +++ b/app/CouponRebate/CouponRebate.php @@ -16,7 +16,8 @@ class CouponRebate implements CouponRebateInterface ->leftjoin('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id') ->where([ ['r.user_id','=',$user_id], - ['u.active_type','=',2] + ['u.active_type','=',2], + ['u.receive_type','=',4] ]) ->select('r.id') ->first(); From 2ddda3a71dd08a0ffeaf75473a1210556dc1591b Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 4 Aug 2020 17:16:45 +0800 Subject: [PATCH 031/172] =?UTF-8?q?=E9=A2=86=E5=88=B8=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/CouponRebate/CouponRebate.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/CouponRebate/CouponRebate.php b/app/CouponRebate/CouponRebate.php index 85cf4e5..60438a1 100644 --- a/app/CouponRebate/CouponRebate.php +++ b/app/CouponRebate/CouponRebate.php @@ -16,8 +16,8 @@ class CouponRebate implements CouponRebateInterface ->leftjoin('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id') ->where([ ['r.user_id','=',$user_id], + ['r.receive_type','=',4], ['u.active_type','=',2], - ['u.receive_type','=',4] ]) ->select('r.id') ->first(); From 2c7c43fdc8a042c67dfb677a40059af2e094cba1 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 4 Aug 2020 17:44:12 +0800 Subject: [PATCH 032/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8--=E9=A2=86=E5=8F=96=E4=BC=98=E6=83=A0=E5=88=B8?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 2 +- config/routes.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 89e1cd3..119ac36 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -38,7 +38,7 @@ class CouponRebateController extends BaseController /** * 用户领取优惠券 */ - public function userReceiveCouponA(CouponRebateReceiveRequest $validator) + public function userReceiveCoupon(CouponRebateReceiveRequest $validator) { $userId = $this->request->input("user_id", 0); $receiveType = $this->request->input("receive_type", 0); diff --git a/config/routes.php b/config/routes.php index 0b238a6..547837f 100644 --- a/config/routes.php +++ b/config/routes.php @@ -27,5 +27,5 @@ Router::addGroup('/v1/',function (){ Router::post('ParamsToken/analyze', 'App\Controller\ParamsTokenController@analyze'); Router::post('Ad/banners', 'App\Controller\AdController@banners'); Router::post('CouponRebate/isCouponRebate', 'App\Controller\CouponRebateController@isCouponRebate'); - Router::post('CouponRebate/userReceiveCoupon', 'App\Controller\CouponRebateController@userReceiveCouponA'); + Router::post('CouponRebate/userReceiveCoupon', 'App\Controller\CouponRebateController@userReceiveCoupon'); }); \ No newline at end of file From fd64e9a5ab5141301a810838cc2461787409b799 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 4 Aug 2020 18:00:19 +0800 Subject: [PATCH 033/172] =?UTF-8?q?=E8=BF=94=E5=88=B8=E6=B4=BB=E5=8A=A8?= =?UTF-8?q?=E8=AF=A6=E7=BB=86=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 12 ++++++++++++ app/CouponRebate/CouponRebate.php | 10 ++++++++++ app/CouponRebate/CouponRebateInterface.php | 2 ++ config/routes.php | 1 + 4 files changed, 25 insertions(+) diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 89e1cd3..3c1ee3d 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -28,6 +28,9 @@ class CouponRebateController extends BaseController * @var CouponRebateInterface */ protected $CouponRebate; + /** + * 用户是否领取过领取优惠券 + */ public function isCouponRebate() { $user_id = $this->request->input('user_id', 0); @@ -35,6 +38,15 @@ class CouponRebateController extends BaseController return $this->success($res); } + /** + * 返回活动信息 + */ + public function getActiveInfo() + { + $res = $this->CouponRebate->getActiveInfo(); + return $this->success($res); + } + /** * 用户领取优惠券 */ diff --git a/app/CouponRebate/CouponRebate.php b/app/CouponRebate/CouponRebate.php index 60438a1..d61e2d8 100644 --- a/app/CouponRebate/CouponRebate.php +++ b/app/CouponRebate/CouponRebate.php @@ -24,4 +24,14 @@ class CouponRebate implements CouponRebateInterface return $res; } + public function getActiveInfo() + { + $res = Db::table('ims_system_coupon_user') + ->where([ + ['active_type','=',2], + ]) + ->get(); + return $res; + } + } \ No newline at end of file diff --git a/app/CouponRebate/CouponRebateInterface.php b/app/CouponRebate/CouponRebateInterface.php index 8c63313..385f1a7 100644 --- a/app/CouponRebate/CouponRebateInterface.php +++ b/app/CouponRebate/CouponRebateInterface.php @@ -7,4 +7,6 @@ interface CouponRebateInterface public function isCouponRebate($user_id); + public function getActiveInfo(); + } \ No newline at end of file diff --git a/config/routes.php b/config/routes.php index 0b238a6..86c239d 100644 --- a/config/routes.php +++ b/config/routes.php @@ -28,4 +28,5 @@ Router::addGroup('/v1/',function (){ Router::post('Ad/banners', 'App\Controller\AdController@banners'); Router::post('CouponRebate/isCouponRebate', 'App\Controller\CouponRebateController@isCouponRebate'); Router::post('CouponRebate/userReceiveCoupon', 'App\Controller\CouponRebateController@userReceiveCouponA'); + Router::post('CouponRebate/getActiveInfo', 'App\Controller\CouponRebateController@getActiveInfo'); }); \ No newline at end of file From e74b37a25650598349c96ed10add87fd9cf3f78b Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 4 Aug 2020 18:48:53 +0800 Subject: [PATCH 034/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8--=E4=BF=AE=E6=94=B9=E9=A2=86=E5=88=B8=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 126 +++++++++++---------- app/Request/CouponRebateReceiveRequest.php | 6 +- 2 files changed, 67 insertions(+), 65 deletions(-) diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 119ac36..9c78b87 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -36,91 +36,93 @@ class CouponRebateController extends BaseController } /** - * 用户领取优惠券 + * 用户领取优惠券 2020.08.04 只领一张 */ public function userReceiveCoupon(CouponRebateReceiveRequest $validator) { $userId = $this->request->input("user_id", 0); $receiveType = $this->request->input("receive_type", 0); - $ids = $this->request->input("ids", ''); + $id = $this->request->input("id", 0); $sendUserId = $this->request->input("send_user_id", 0); $phone = $this->request->input("phone", ''); - $ids = explode(',', $ids); $now = time(); + // status : 0 领取成功 >0 领取失败 + $return = [ + 'status' => 1, + 'data' => [], + 'coupon_text' => '继续努力~' + ]; // mock 数据 给前端用 $test = $this->request->input("test", 0); if($test){ - $cps = Coupon::whereIn('id', $ids)->lockForUpdate() - ->select('id','title','status','inventory','inventory_use','start_time','end_time') + $cps = Coupon::where('id', $id)->lockForUpdate() + ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts') ->first(); - return $this->success([ - 'success' => [$cps], - 'fail' => [], - ]); + $return['status'] = 0; + $return['data'] = $cps; + $return['coupon_text'] = $cps['discounts'].'元红包'; + return $this->success($return); } - $success = []; - $fail = []; - - Db::transaction( function () use ($ids,$receiveType,$userId,$sendUserId,$phone,&$success,&$fail,$now) { + Db::transaction( function () use ($id,$receiveType,$userId,$sendUserId,$phone,&$success,&$fail,$now) { //读写锁,完全控制,性能低 - $cps = Coupon::whereIn('id', $ids)->lockForUpdate() - ->select('id','title','status','inventory','inventory_use','start_time','end_time') - ->get(); - - foreach ($cps as $key => $cp) { + $cp = Coupon::where('id', $id)->lockForUpdate() + ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts') + ->first(); - $where = [ - 'system_coupon_user_id' => $cp->id, - ]; + $where = [ + 'system_coupon_user_id' => $cp->id, + ]; - if (env('SUB_CHANNEL') == 1) { - $where['receive_type'] = $receiveType; - } + if (env('SUB_CHANNEL') == 1) { + $where['receive_type'] = $receiveType; + } + // 查询领取类型一次能领取的数量 + $crt = CouponUserRecType::where($where)->first(); - $crt = CouponUserRecType::where($where)->first(); + $cr = new CouponRec; + $cr->user_id = $userId; + $cr->system_coupon_user_id = $cp->id; + $cr->order_main_id = 0; + $cr->receive_time = $now; + $cr->number = $crt->one_receive_number; + $cr->number_remain = $crt->one_receive_number; + $cr->status = 0; + $cr->update_time = $now; + $cr->receive_type = $receiveType; + $cr->send_user_id = $sendUserId; + $cr->phone = $phone; - $cr = new CouponRec; - $cr->user_id = $userId; - $cr->system_coupon_user_id = $cp->id; - $cr->order_main_id = 0; - $cr->receive_time = $now; - $cr->number = $crt->one_receive_number; - $cr->number_remain = $crt->one_receive_number; - $cr->status = 0; - $cr->update_time = $now; - $cr->receive_type = $receiveType; - $cr->send_user_id = $sendUserId; - $cr->phone = $phone; - //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内, 则返回领取失败的优惠券 - if ( - $cp->status != 1 - || - $cp->inventory <= $cp->inventory_use - || - $cp->inventory < ($cp->inventory_use+$cr->number) - || - $cp->start_time < $now - || - $cp->end_time > $now - ) - { - $fail[] = $cp; - }else{ - $cp->inventory_use += $cr->number;//记录已领取的数量 - if ( $cr->save() && $cp->save() ) { - $success[] = $cp; - } else { - $fail[] = $cp; - } + //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内, 则返回领取失败的优惠券 + if ( + $cp->status != 1 + || + $cp->inventory <= $cp->inventory_use + || + $cp->inventory < ($cp->inventory_use+$cr->number) + || + $cp->start_time < $now + || + $cp->end_time > $now + ) + { + $return['status'] = 2; + $return['coupon_text'] = '红包已经领完~'; + }else{ + $cp->inventory_use += $cr->number;//记录已领取的数量 + if ( $cr->save() && $cp->save() ) { + $return['status'] = 0; + $return['data'] = $cps; + $return['coupon_text'] = $cps['discounts'].'元红包'; + } else { + $return['status'] = 3; + $return['coupon_text'] = '下次继续努力~'; } } + }); - return $this->success([ - 'success' => $success, - 'fail' => $fail, - ]); + return $this->success($return); } } diff --git a/app/Request/CouponRebateReceiveRequest.php b/app/Request/CouponRebateReceiveRequest.php index 4c4beed..3169c3e 100644 --- a/app/Request/CouponRebateReceiveRequest.php +++ b/app/Request/CouponRebateReceiveRequest.php @@ -24,7 +24,7 @@ class CouponRebateReceiveRequest extends FormRequest return [ 'user_id' => 'required|nonempty|integer|exists_enable:ims_cjdc_user,id', 'receive_type' => 'required|nonempty|integer', - 'ids' => 'required|nonempty', + 'id' => 'required|nonempty', ]; } @@ -33,7 +33,7 @@ class CouponRebateReceiveRequest extends FormRequest return [ 'user_id.*' => ':attribute信息不正确', 'receive_type.*' => ':attribute必须', - 'ids.*' => ':attribute必须', + 'id.*' => ':attribute必须', ]; } @@ -42,7 +42,7 @@ class CouponRebateReceiveRequest extends FormRequest return [ 'user_id' => '领取用户ID', 'receive_type' => '领取方式', - 'ids' => '优惠券', + 'id' => '优惠券', ]; } } From 2b3adc7245e65ea79fc0ff3714ccc4bed2e1c3a5 Mon Sep 17 00:00:00 2001 From: weigang Date: Tue, 4 Aug 2020 19:59:56 +0800 Subject: [PATCH 035/172] =?UTF-8?q?=E8=AF=AD=E9=9F=B3=E6=92=AD=E6=8A=A5?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E6=B5=81=E7=A8=8B=E8=B5=B0=E5=AE=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 37 ++++++++-- app/Constants/LogLabel.php | 24 +++++++ app/Controller/DeviceController.php | 73 ++++++++++++++++--- app/Model/Order.php | 10 +++ app/Model/OrderMain.php | 10 +++ app/Model/Store.php | 9 +++ app/Service/DeviceServiceImp.php | 88 ++++++++++++++++++++--- app/Service/DeviceServiceInterFace.php | 3 +- app/Service/IOTAliService.php | 54 ++++++++++++++ app/Service/IOTServiceInterface.php | 8 +++ app/TaskWorker/AliIotTask.php | 89 ++++++++---------------- config/autoload/dependencies.php | 1 + config/routes.php | 1 + 13 files changed, 323 insertions(+), 84 deletions(-) create mode 100644 app/Constants/LogLabel.php create mode 100644 app/Model/Order.php create mode 100644 app/Model/OrderMain.php create mode 100644 app/Model/Store.php create mode 100644 app/Service/IOTAliService.php create mode 100644 app/Service/IOTServiceInterface.php diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index ea4cc7d..773f0dd 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -4,26 +4,51 @@ declare(strict_types=1); namespace App\Amqp\Consumer; +use App\Model\Order; +use App\Model\SpeakerDevic; +use App\Service\DeviceServiceInterFace; use Hyperf\Amqp\Result; use Hyperf\Amqp\Annotation\Consumer; use Hyperf\Amqp\Message\ConsumerMessage; +use Hyperf\DbConnection\Db; use PhpAmqpLib\Message\AMQPMessage; +use Hyperf\Di\Annotation\Inject; /** * @Consumer(exchange="devicOrder", routingKey="devicOrder", queue="devicOrder", nums=1) */ class DevicOrderConsumer extends ConsumerMessage { - private $msgCount = 0; + /** + * @Inject + * @var DeviceServiceInterFace + */ + protected $deviceService; + public function consumeMessage($data, AMQPMessage $message): string { - var_dump($data); - var_dump($message->getBody()); - if($this->msgCount< 10){ - $this->msgCount += 1; + try { + + $orderMainId = $message->getBody(); + $order = Order::query() + ->select(['id', 'store_id', 'money']) + ->where(['order_main_id' => $orderMainId, 'type' => 4, 'dm_state' => 2]) + ->first(); + + $deviceName = SpeakerDevic::query()->where(['store_id' => $order['store_id']])->value('device_name'); + + $msg = "{\"msg\":\"到账".$order['money']."元\"}"; + $res = $this->deviceService->pubMsgToStoreByDevName($deviceName, $msg); + + if ($res == true) { + return Result::ACK; + } else { + return Result::REQUEUE; + } + + } catch (\Exception $e) { return Result::REQUEUE; } - return Result::ACK; } public function isEnable(): bool diff --git a/app/Constants/LogLabel.php b/app/Constants/LogLabel.php new file mode 100644 index 0000000..b3cadb4 --- /dev/null +++ b/app/Constants/LogLabel.php @@ -0,0 +1,24 @@ + 'required|nonempty|integer', 'device_name' => 'required|nonempty|alpha_num', - ], [ 'store_id.required' => '参数不正确', @@ -36,24 +35,80 @@ class DeviceController extends BaseController ] ); - if ($validator->fails()){ + if ($validator->fails()) { // Handle exception - $errorMessage = $validator->errors()->first(); - $this->result(200,[],$errorMessage); + throw new ValidationException($validator); + return; } - $store_id = $this->request->input('store_id'); $device_name = $this->request->input('device_name'); - $sd = $this->deviceService->bindByStoreId($device_name,$store_id); + $sd = $this->deviceService->bindByStoreId($device_name, $store_id); - return $this->result(0,[$sd],'绑定成功'); + if (is_null($sd)) { + return $this->result(100, '', '绑定失败: 设备号已经被绑定或不存在'); + } + + return $this->success($sd, '绑定成功'); } public function list() { - + $validator = $this->validationFactory->make( + $this->request->all(), + [ + 'store_id' => 'required|nonempty|integer', + ], + [ + 'store_id.required' => '参数不正确', + 'store_id.nonempty' => '参数不正确', + 'store_id.integer' => '参数不正确', + ] + ); + + if ($validator->fails()) { + // Handle exception + throw new ValidationException($validator); + return; + } + + $store_id = $this->request->input('store_id'); + + $devices = $this->deviceService->getListByStoreId($store_id); + + return $this->success($devices); + } + + public function unbind() + { + $validator = $this->validationFactory->make( + $this->request->all(), + [ + 'bind_id' => 'required|nonempty|integer', + ], + [ + 'bind_id.required' => '参数不正确', + 'bind_id.nonempty' => '参数不正确', + 'bind_id.integer' => '参数不正确', + ] + ); + + if ($validator->fails()) { + // Handle exception + throw new ValidationException($validator); + return; + } + + $bind_id = $this->request->input('bind_id'); + + $unbind_num = $this->deviceService->unbindById($bind_id); + + if ($unbind_num == 0) { + return $this->result(100, '', '解绑失败: 设备已经解绑或不存在'); + } + + return $this->success(['unbind' => $unbind_num]); } } \ No newline at end of file diff --git a/app/Model/Order.php b/app/Model/Order.php new file mode 100644 index 0000000..0a5bdd4 --- /dev/null +++ b/app/Model/Order.php @@ -0,0 +1,10 @@ +where(['store_id' => $store_id])->get(); } - public function bindByStoreId($dev_name,$store_id){ + + /** + * 绑定 + * @param $dev_name + * @param $store_id + * @return SpeakerDevic|null + * @throws \Throwable + */ + public function bindByStoreId($dev_name, $store_id) + { $sd = null; - try{ - $sd = new SpeakerDevic; + + if ($this->checkDeviceEnable($dev_name)) { + return $sd; + } + + try { + + // 获取市场ID + $market_id = Store::query()->where(['id' => $store_id])->value('market_id'); + + $sd = new SpeakerDevic; $sd->store_id = $store_id; $sd->device_name = $dev_name; - $sd->market_id = 1; + $sd->market_id = $market_id; $sd->bind_time = time(); $sd->saveOrFail(); - }catch(Exception $e){ - //var_dump($e); + } catch (Exception $e) { + $this->log->event(LogLabel::DEVICE_LOG, ['msg' => '绑定设备异常:'.$e->getMessage()]); } return $sd; } - public function pubMsgByStoreIdAndDevName($dev_name,$store_id,$msg){ + /** + * 解绑 + * @param $bind_id + * @return int + */ + public function unbindById($bind_id) + { + return SpeakerDevic::destroy($bind_id); + } + + /** + * 发布语音消息 + * @param $store_id + * @param $msg + */ + public function pubMsgToStoreByDevName($dev_name, $msg) + { + return $this->IOTService->pub($dev_name, $msg); } + + /** + * 当前设备是否已经被绑定 + * @param $dev_name + * @return bool + */ + protected function checkDeviceEnable($dev_name) + { + return SpeakerDevic::query()->where(['device_name' => $dev_name])->exists(); + } + } \ No newline at end of file diff --git a/app/Service/DeviceServiceInterFace.php b/app/Service/DeviceServiceInterFace.php index e22e184..2bb9cb0 100644 --- a/app/Service/DeviceServiceInterFace.php +++ b/app/Service/DeviceServiceInterFace.php @@ -6,5 +6,6 @@ interface DeviceServiceInterFace { public function getListByStoreId($store_id); public function bindByStoreId($dev_name,$store_id); - public function pubMsgByStoreIdAndDevName($dev_name,$store_id,$msg); + public function unbindById($bind_id); + public function pubMsgToStoreByDevName($dev_name,$msg); } \ No newline at end of file diff --git a/app/Service/IOTAliService.php b/app/Service/IOTAliService.php new file mode 100644 index 0000000..6b8a854 --- /dev/null +++ b/app/Service/IOTAliService.php @@ -0,0 +1,54 @@ +regionId(env('ALI_IOT_REGION')) + ->asDefaultClient(); + + try { + AlibabaCloud::rpc() + ->product('Iot') + ->version('2018-01-20') + ->action('Pub') + ->method('POST') + ->host(env('ALI_IOT_HOST')) + ->options([ + 'query' => [ + 'RegionId' => "cn-shanghai", + 'TopicFullName' => "/a1ZSurIJmO0/".$device_name."/user/get", + 'MessageContent' => base64_encode($msg), + 'ProductKey' => env('ALI_IOT_PRODUCT_KEY'), + ], + ]) + ->request(); + } catch (ClientException $e) { + $this->log->event(LogLabel::DEVICE_LOG, ['msg' => 'ClientException发布失败:'.$e->getErrorMessage()]); + return false; + } catch (ServerException $e) { + $this->log->event(LogLabel::DEVICE_LOG, ['msg' => 'ServerException发布失败:'.$e->getErrorMessage()]); + return false; + } + + return true; + } + +} \ No newline at end of file diff --git a/app/Service/IOTServiceInterface.php b/app/Service/IOTServiceInterface.php new file mode 100644 index 0000000..931aca6 --- /dev/null +++ b/app/Service/IOTServiceInterface.php @@ -0,0 +1,8 @@ +regionId('cn-shanghai') - ->asDefaultClient(); - $result2 = ''; - - $msg = "{\"msg\":\"收款123元\"}"; - try{ - AlibabaCloud::rpc() - ->product('Iot') - // ->scheme('https') // https | http - ->version('2018-01-20') - ->action('Pub') - ->method('POST') - ->host('iot.cn-shanghai.aliyuncs.com') - ->options([ - 'query' => [ - 'RegionId' => "cn-shanghai", - 'TopicFullName' => "/a1ZSurIJmO0/BOX0000000000003/user/get", - 'MessageContent' => base64_encode($msg), - 'ProductKey' => "a1ZSurIJmO0", - ], - ]) - ->request(); - //var_dump($result2->toArray()); + ->regionId('cn-shanghai') + ->asDefaultClient(); + + try { + AlibabaCloud::rpc() + ->product('Iot') + ->version('2018-01-20') + ->action('Pub') + ->method('POST') + ->host('iot.cn-shanghai.aliyuncs.com') + ->options([ + 'query' => [ + 'RegionId' => "cn-shanghai", + 'TopicFullName' => "/a1ZSurIJmO0/".$device_name."/user/get", + 'MessageContent' => base64_encode($msg), + 'ProductKey' => "a1ZSurIJmO0", + ], + ]) + ->request(); } catch (ClientException $e) { echo $e->getErrorMessage() . PHP_EOL; } catch (ServerException $e) { echo $e->getErrorMessage() . PHP_EOL; } - //print_r($response); - return ""; + return true; } -// protected function getClient(){ -// AlibabaCloud::accessKeyClient('LTAI4GJEWrN6dVh7HmPKHMyF', 'wMae4ckfVGwMQPVw5ZlVDDpihVeUap') -// ->regionId('cn-shanghai') -// ->asDefaultClient(); -// $result = ''; - -// $msg = "{\"msg\":\"收款123元\"}"; -// try{ -// $result = AlibabaCloud::rpc() -// ->product('Iot') -// // ->scheme('https') // https | http -// ->version('2018-01-20') -// ->action('Pub') -// ->method('POST') -// ->host('iot.cn-shanghai.aliyuncs.com') -// ->options([ -// 'query' => [ -// 'RegionId' => "cn-shanghai", -// 'TopicFullName' => "/a1ZSurIJmO0/BOX0000000000003/user/get", -// 'MessageContent' => base64_encode($msg), -// 'ProductKey' => "a1ZSurIJmO0", -// ], -// ]) -// ->request(); -// var_dump($result->toArray()); -// } catch (ClientException $e) { -// echo $e->getErrorMessage() . PHP_EOL; -// } catch (ServerException $e) { -// echo $e->getErrorMessage() . PHP_EOL; -// } -// return $result; - -// } } diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 4b46ec8..c147e40 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -15,4 +15,5 @@ return [ \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, \App\Service\DeviceServiceInterFace::class =>\App\Service\DeviceServiceImp::class, \App\Commons\Log::class => \App\Commons\Log::class, + \App\Service\IOTServiceInterface::class => \App\Service\IOTAliService::class, ]; diff --git a/config/routes.php b/config/routes.php index 0eebd7e..a067b45 100644 --- a/config/routes.php +++ b/config/routes.php @@ -32,6 +32,7 @@ Router::addGroup('/v1/',function (){ //播报器相关 Router::post('Device/bind', 'App\Controller\DeviceController@bind'); Router::post('Device/list', 'App\Controller\DeviceController@list'); + Router::post('Device/unbind', 'App\Controller\DeviceController@unbind'); //测试路由 Router::get('test/index1', 'App\Controller\TestController@index1'); From 22fe7c27aab85a8e94595f8732bda4ef50d5cd90 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 4 Aug 2020 20:04:57 +0800 Subject: [PATCH 036/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8--=E5=88=A0=E9=99=A4mock=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 202a0a3..39fbb14 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -67,17 +67,6 @@ class CouponRebateController extends BaseController 'data' => [], 'coupon_text' => '继续努力~' ]; - // mock 数据 给前端用 - $test = $this->request->input("test", 0); - if($test){ - $cps = Coupon::where('id', $id)->lockForUpdate() - ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts') - ->first(); - $return['status'] = 0; - $return['data'] = $cps; - $return['coupon_text'] = $cps['discounts'].'元红包'; - return $this->success($return); - } Db::transaction( function () use ($id,$receiveType,$userId,$sendUserId,$phone,&$return,$now) { //读写锁,完全控制,性能低 From cd72658a2f2a0e55a57c3081c23edfe80eda35f6 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 4 Aug 2020 20:32:52 +0800 Subject: [PATCH 037/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8--=E9=A2=86=E5=8F=96=E6=8E=A5=E5=8F=A3-=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 39fbb14..1c856f3 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -50,7 +50,7 @@ class CouponRebateController extends BaseController /** * 用户领取优惠券 - * 用户领取优惠券 2020.08.04 只领一张 + * 2020.08.04 只领一张优惠券 */ public function userReceiveCoupon(CouponRebateReceiveRequest $validator) { @@ -73,7 +73,7 @@ class CouponRebateController extends BaseController $cp = Coupon::where('id', $id)->lockForUpdate() ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts') ->first(); - + $where = [ 'system_coupon_user_id' => $cp->id, ]; @@ -83,7 +83,7 @@ class CouponRebateController extends BaseController } // 查询领取类型一次能领取的数量 $crt = CouponUserRecType::where($where)->first(); - + $cr = new CouponRec; $cr->user_id = $userId; $cr->system_coupon_user_id = $cp->id; @@ -96,7 +96,7 @@ class CouponRebateController extends BaseController $cr->receive_type = $receiveType; $cr->send_user_id = $sendUserId; $cr->phone = $phone; - + //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内, 则返回领取失败的优惠券 if ( $cp->status != 1 @@ -105,9 +105,9 @@ class CouponRebateController extends BaseController || $cp->inventory < ($cp->inventory_use+$cr->number) || - $cp->start_time < $now + $cp->start_time > $now || - $cp->end_time > $now + $cp->end_time < $now ) { $return['status'] = 2; @@ -116,11 +116,8 @@ class CouponRebateController extends BaseController $cp->inventory_use += $cr->number;//记录已领取的数量 if ( $cr->save() && $cp->save() ) { $return['status'] = 0; - $return['data'] = $cps; - $return['coupon_text'] = $cps['discounts'].'元红包'; - } else { - $return['status'] = 3; - $return['coupon_text'] = '下次继续努力~'; + $return['data'] = $cp; + $return['coupon_text'] = $cp['discounts'].'元红包'; } } From 901c91ae49b935dbe3248fcf00782bc773597486 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 4 Aug 2020 20:52:09 +0800 Subject: [PATCH 038/172] =?UTF-8?q?=E6=B4=BB=E5=8A=A8=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/CouponRebate/CouponRebate.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/CouponRebate/CouponRebate.php b/app/CouponRebate/CouponRebate.php index d61e2d8..510e99b 100644 --- a/app/CouponRebate/CouponRebate.php +++ b/app/CouponRebate/CouponRebate.php @@ -26,10 +26,15 @@ class CouponRebate implements CouponRebateInterface public function getActiveInfo() { + $time = time(); $res = Db::table('ims_system_coupon_user') ->where([ + ['status','=',1], ['active_type','=',2], + ['start_time','<=',$time], + ['end_time','>',$time], ]) + ->whereRaw('inventory > inventory_use') ->get(); return $res; } From ba181d6fb3ace7661932c20f370c0c16eb036fa0 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 5 Aug 2020 09:11:04 +0800 Subject: [PATCH 039/172] =?UTF-8?q?=E8=AF=AD=E9=9F=B3=E6=92=AD=E6=8A=A5?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E4=B8=8D=E5=AD=98=E5=9C=A8=E6=88=96=E8=AE=BE?= =?UTF-8?q?=E5=A4=87=E5=8F=B7=E4=B8=8D=E5=AD=98=E5=9C=A8=E6=89=93=E5=9B=9E?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index 773f0dd..2bf258a 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -35,8 +35,16 @@ class DevicOrderConsumer extends ConsumerMessage ->where(['order_main_id' => $orderMainId, 'type' => 4, 'dm_state' => 2]) ->first(); + if (is_null($order)||!$order) { + return Result::REQUEUE; + } + $deviceName = SpeakerDevic::query()->where(['store_id' => $order['store_id']])->value('device_name'); + if (is_null($deviceName)||!$deviceName) { + return Result::REQUEUE; + } + $msg = "{\"msg\":\"到账".$order['money']."元\"}"; $res = $this->deviceService->pubMsgToStoreByDevName($deviceName, $msg); From 58c1f57d699c81af6cdc652c0ca606295c30e11a Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Wed, 5 Aug 2020 09:38:52 +0800 Subject: [PATCH 040/172] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 2 +- app/{CouponRebate => Service}/CouponRebate.php | 2 +- app/{CouponRebate => Service}/CouponRebateInterface.php | 2 +- config/autoload/dependencies.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) rename app/{CouponRebate => Service}/CouponRebate.php (97%) rename app/{CouponRebate => Service}/CouponRebateInterface.php (81%) diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 1c856f3..8cdfd9a 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -14,7 +14,7 @@ namespace App\Controller; use Hyperf\DbConnection\Db; use Hyperf\Redis\Redis; use Hyperf\Utils\ApplicationContext; -use App\CouponRebate\CouponRebateInterface; +use App\Service\CouponRebateInterface; use http\Client\Curl\User; use Hyperf\Di\Annotation\Inject; use App\Model\Coupon; diff --git a/app/CouponRebate/CouponRebate.php b/app/Service/CouponRebate.php similarity index 97% rename from app/CouponRebate/CouponRebate.php rename to app/Service/CouponRebate.php index 510e99b..a171bb8 100644 --- a/app/CouponRebate/CouponRebate.php +++ b/app/Service/CouponRebate.php @@ -1,6 +1,6 @@ \App\Service\ParamsTokenSsdbService::class, \App\Service\AdServiceInterface::class => \App\Service\AdService::class, \App\Commons\Log::class => \App\Commons\Log::class, - \App\CouponRebate\CouponRebateInterface::class => \App\CouponRebate\CouponRebate::class, + \App\Service\CouponRebateInterface::class => \App\Service\CouponRebate::class, ]; From cae320969fe8ea51b70c85539909336755c39087 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 5 Aug 2020 11:25:31 +0800 Subject: [PATCH 041/172] =?UTF-8?q?=E6=96=B0=E5=A2=9EIS=5FBIND=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E7=9B=B8=E5=85=B3=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 14 +++++++---- app/Model/SpeakerDevic.php | 5 ++++ app/Service/DeviceServiceImp.php | 32 ++++++++++++++++-------- app/Service/DeviceServiceInterFace.php | 2 +- app/Service/IOTAliService.php | 2 +- 5 files changed, 37 insertions(+), 18 deletions(-) diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index 2bf258a..8ba1935 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -15,7 +15,7 @@ use PhpAmqpLib\Message\AMQPMessage; use Hyperf\Di\Annotation\Inject; /** - * @Consumer(exchange="devicOrder", routingKey="devicOrder", queue="devicOrder", nums=1) + * @Consumer(exchange="devicOrder", routingKey="devicOrder", queue="devicOrder", nums=4) */ class DevicOrderConsumer extends ConsumerMessage { @@ -39,14 +39,18 @@ class DevicOrderConsumer extends ConsumerMessage return Result::REQUEUE; } - $deviceName = SpeakerDevic::query()->where(['store_id' => $order['store_id']])->value('device_name'); + $deviceNames = SpeakerDevic::query() + ->select(['device_name']) + ->where(['store_id' => $order['store_id'], 'is_bind' => SpeakerDevic::IS_BIND_YES]) + ->get() + ->toArray(); - if (is_null($deviceName)||!$deviceName) { + if (empty($deviceNames)||!$deviceNames) { return Result::REQUEUE; } $msg = "{\"msg\":\"到账".$order['money']."元\"}"; - $res = $this->deviceService->pubMsgToStoreByDevName($deviceName, $msg); + $res = $this->deviceService->pubMsgToStoreByDevName($deviceNames, $msg); if ($res == true) { return Result::ACK; @@ -61,7 +65,7 @@ class DevicOrderConsumer extends ConsumerMessage public function isEnable(): bool { - //if(env('APP_ENV')!='prod') return false; + // if(env('APP_ENV')!='prod') return false; return parent::isEnable(); } } diff --git a/app/Model/SpeakerDevic.php b/app/Model/SpeakerDevic.php index 4512111..4c4816e 100644 --- a/app/Model/SpeakerDevic.php +++ b/app/Model/SpeakerDevic.php @@ -6,6 +6,11 @@ use App\Model\Model; class SpeakerDevic extends Model { + const IS_BIND_YES = 1; + const IS_BIND_NO = 0; + protected $table = 'lanzu_service_speakers'; + protected $fillable = ['store_id', 'device_name', 'state', 'market_id', 'bind_time', 'is_bind']; + } \ No newline at end of file diff --git a/app/Service/DeviceServiceImp.php b/app/Service/DeviceServiceImp.php index 3d27426..61744c2 100644 --- a/app/Service/DeviceServiceImp.php +++ b/app/Service/DeviceServiceImp.php @@ -31,7 +31,7 @@ class DeviceServiceImp implements DeviceServiceInterFace */ public function getListByStoreId($store_id) { - return SpeakerDevic::query()->where(['store_id' => $store_id])->get(); + return SpeakerDevic::query()->where(['store_id' => $store_id, 'is_bind' => SpeakerDevic::IS_BIND_YES])->get()->toArray(); } /** @@ -54,12 +54,18 @@ class DeviceServiceImp implements DeviceServiceInterFace // 获取市场ID $market_id = Store::query()->where(['id' => $store_id])->value('market_id'); - $sd = new SpeakerDevic; - $sd->store_id = $store_id; - $sd->device_name = $dev_name; - $sd->market_id = $market_id; - $sd->bind_time = time(); - $sd->saveOrFail(); + // $sd = new SpeakerDevic; + // $sd->store_id = $store_id; + // $sd->device_name = $dev_name; + // $sd->market_id = $market_id; + // $sd->bind_time = time(); + // $sd->saveOrFail(); + + $sd = SpeakerDevic::query()->updateOrCreate( + ['store_id' => $store_id, 'device_name' => $dev_name], + ['market_id' => $market_id, 'bind_time' => time(), 'is_bind' => SpeakerDevic::IS_BIND_YES] + ); + } catch (Exception $e) { $this->log->event(LogLabel::DEVICE_LOG, ['msg' => '绑定设备异常:'.$e->getMessage()]); } @@ -73,7 +79,7 @@ class DeviceServiceImp implements DeviceServiceInterFace */ public function unbindById($bind_id) { - return SpeakerDevic::destroy($bind_id); + return SpeakerDevic::query()->where(['id' => $bind_id])->update(['is_bind' => SpeakerDevic::IS_BIND_NO]); } /** @@ -81,9 +87,13 @@ class DeviceServiceImp implements DeviceServiceInterFace * @param $store_id * @param $msg */ - public function pubMsgToStoreByDevName($dev_name, $msg) + public function pubMsgToStoreByDevName($dev_names, $msg) { - return $this->IOTService->pub($dev_name, $msg); + foreach ($dev_names as $key => $dev_name) { + $this->IOTService->pub($dev_name, $msg); + } + + return true; } /** @@ -93,7 +103,7 @@ class DeviceServiceImp implements DeviceServiceInterFace */ protected function checkDeviceEnable($dev_name) { - return SpeakerDevic::query()->where(['device_name' => $dev_name])->exists(); + return SpeakerDevic::query()->where(['device_name' => $dev_name, 'is_bind' => SpeakerDevic::IS_BIND_YES])->exists(); } } \ No newline at end of file diff --git a/app/Service/DeviceServiceInterFace.php b/app/Service/DeviceServiceInterFace.php index 2bb9cb0..15aa23b 100644 --- a/app/Service/DeviceServiceInterFace.php +++ b/app/Service/DeviceServiceInterFace.php @@ -7,5 +7,5 @@ interface DeviceServiceInterFace public function getListByStoreId($store_id); public function bindByStoreId($dev_name,$store_id); public function unbindById($bind_id); - public function pubMsgToStoreByDevName($dev_name,$msg); + public function pubMsgToStoreByDevName($dev_names,$msg); } \ No newline at end of file diff --git a/app/Service/IOTAliService.php b/app/Service/IOTAliService.php index 6b8a854..88c4d4c 100644 --- a/app/Service/IOTAliService.php +++ b/app/Service/IOTAliService.php @@ -34,7 +34,7 @@ class IOTAliService implements IOTServiceInterface ->options([ 'query' => [ 'RegionId' => "cn-shanghai", - 'TopicFullName' => "/a1ZSurIJmO0/".$device_name."/user/get", + 'TopicFullName' => "/".env('ALI_IOT_PRODUCT_KEY')."/".$device_name."/user/get", 'MessageContent' => base64_encode($msg), 'ProductKey' => env('ALI_IOT_PRODUCT_KEY'), ], From b81edf8cd558ffca3ba77beba446c1d19ed8873f Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 5 Aug 2020 11:32:03 +0800 Subject: [PATCH 042/172] =?UTF-8?q?=E8=AE=A2=E5=8D=95=E6=88=96=E8=AE=BE?= =?UTF-8?q?=E5=A4=87=E5=8F=B7=E5=BC=82=E5=B8=B8=E7=9B=B4=E6=8E=A5ACK?= =?UTF-8?q?=E5=BA=94=E7=AD=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index 8ba1935..d0aa997 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -36,7 +36,7 @@ class DevicOrderConsumer extends ConsumerMessage ->first(); if (is_null($order)||!$order) { - return Result::REQUEUE; + return Result::ACK; } $deviceNames = SpeakerDevic::query() @@ -46,7 +46,7 @@ class DevicOrderConsumer extends ConsumerMessage ->toArray(); if (empty($deviceNames)||!$deviceNames) { - return Result::REQUEUE; + return Result::ACK; } $msg = "{\"msg\":\"到账".$order['money']."元\"}"; From 96655993183d2bd3f02d42567cd0dfb17a503e78 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Wed, 5 Aug 2020 11:39:37 +0800 Subject: [PATCH 043/172] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebate.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/Service/CouponRebate.php b/app/Service/CouponRebate.php index a171bb8..9f05999 100644 --- a/app/Service/CouponRebate.php +++ b/app/Service/CouponRebate.php @@ -35,6 +35,7 @@ class CouponRebate implements CouponRebateInterface ['end_time','>',$time], ]) ->whereRaw('inventory > inventory_use') + ->orderBy('addtime','desc') ->get(); return $res; } From c46c142f6472e0b191975198d59694e9aaa0c768 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 5 Aug 2020 11:40:41 +0800 Subject: [PATCH 044/172] =?UTF-8?q?=E5=BE=AA=E7=8E=AF=E6=92=AD=E6=8A=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/DeviceServiceImp.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/DeviceServiceImp.php b/app/Service/DeviceServiceImp.php index 61744c2..2b4962c 100644 --- a/app/Service/DeviceServiceImp.php +++ b/app/Service/DeviceServiceImp.php @@ -90,7 +90,7 @@ class DeviceServiceImp implements DeviceServiceInterFace public function pubMsgToStoreByDevName($dev_names, $msg) { foreach ($dev_names as $key => $dev_name) { - $this->IOTService->pub($dev_name, $msg); + $this->IOTService->pub($dev_name['device_name'], $msg); } return true; From 0c9b3f76453a1cf5f97d3116f854f16cdb707827 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Wed, 5 Aug 2020 14:20:24 +0800 Subject: [PATCH 045/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E5=B0=81=E7=AC=AC=E4=B8=80?= =?UTF-8?q?=E7=89=88=EF=BC=88=E9=A2=86=E5=8F=96=E5=8F=AA=E9=A2=86=E4=B8=80?= =?UTF-8?q?=E5=BC=A0=E5=88=B8=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/LogLabel.php | 2 + app/Controller/CouponRebateController.php | 79 ++--------- app/Service/CouponRebateService.php | 135 +++++++++++++++++++ app/Service/CouponRebateServiceInterface.php | 11 ++ 4 files changed, 157 insertions(+), 70 deletions(-) create mode 100644 app/Service/CouponRebateService.php create mode 100644 app/Service/CouponRebateServiceInterface.php diff --git a/app/Constants/LogLabel.php b/app/Constants/LogLabel.php index 2265cf4..c09c8df 100644 --- a/app/Constants/LogLabel.php +++ b/app/Constants/LogLabel.php @@ -16,4 +16,6 @@ class LogLabel extends AbstractConstants * @Message("Ssdb Log Label") */ const SSDB_LOG = 'ssdb_log'; + + const COUPON_LOG = 'coupon_log'; } diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 1c856f3..51f8b78 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -21,6 +21,7 @@ use App\Model\Coupon; use App\Model\CouponUserRecType; use App\Model\CouponRec; use App\Request\CouponRebateReceiveRequest; +use App\Service\CouponRebateService; class CouponRebateController extends BaseController { /** @@ -28,6 +29,13 @@ class CouponRebateController extends BaseController * @var CouponRebateInterface */ protected $CouponRebate; + + /** + * @Inject + * @var CouponRebateService + */ + protected $CouponRebateService; + /** * 用户是否领取过领取优惠券 */ @@ -54,75 +62,6 @@ class CouponRebateController extends BaseController */ public function userReceiveCoupon(CouponRebateReceiveRequest $validator) { - $userId = $this->request->input("user_id", 0); - $receiveType = $this->request->input("receive_type", 0); - $id = $this->request->input("id", 0); - $sendUserId = $this->request->input("send_user_id", 0); - $phone = $this->request->input("phone", ''); - $now = time(); - - // status : 0 领取成功 >0 领取失败 - $return = [ - 'status' => 1, - 'data' => [], - 'coupon_text' => '继续努力~' - ]; - - Db::transaction( function () use ($id,$receiveType,$userId,$sendUserId,$phone,&$return,$now) { - //读写锁,完全控制,性能低 - $cp = Coupon::where('id', $id)->lockForUpdate() - ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts') - ->first(); - - $where = [ - 'system_coupon_user_id' => $cp->id, - ]; - - if (env('SUB_CHANNEL') == 1) { - $where['receive_type'] = $receiveType; - } - // 查询领取类型一次能领取的数量 - $crt = CouponUserRecType::where($where)->first(); - - $cr = new CouponRec; - $cr->user_id = $userId; - $cr->system_coupon_user_id = $cp->id; - $cr->order_main_id = 0; - $cr->receive_time = $now; - $cr->number = $crt->one_receive_number; - $cr->number_remain = $crt->one_receive_number; - $cr->status = 0; - $cr->update_time = $now; - $cr->receive_type = $receiveType; - $cr->send_user_id = $sendUserId; - $cr->phone = $phone; - - //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内, 则返回领取失败的优惠券 - if ( - $cp->status != 1 - || - $cp->inventory <= $cp->inventory_use - || - $cp->inventory < ($cp->inventory_use+$cr->number) - || - $cp->start_time > $now - || - $cp->end_time < $now - ) - { - $return['status'] = 2; - $return['coupon_text'] = '红包已经领完~'; - }else{ - $cp->inventory_use += $cr->number;//记录已领取的数量 - if ( $cr->save() && $cp->save() ) { - $return['status'] = 0; - $return['data'] = $cp; - $return['coupon_text'] = $cp['discounts'].'元红包'; - } - } - - }); - - return $this->success($return); + return $this->success($this->CouponRebateService->userReceiveCoupon($this->request->all())); } } diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php new file mode 100644 index 0000000..cdd384c --- /dev/null +++ b/app/Service/CouponRebateService.php @@ -0,0 +1,135 @@ +0 领取失败 + $result = [ + 'status' => 1, + 'data' => [], + 'coupon_text' => '继续努力~' + ]; + + // 错误日志记录 + $errorData = [ + 'coupon_id' =>$id, + 'user_id' =>$userId, + 'receiveType' =>$receiveType, + 'sendUserId' =>$sendUserId, + 'phone' =>$phone + ]; + + Db::transaction( function() use ($id,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData) { + + try{ + //读写锁,完全控制,性能低 + $cp = Coupon::where('id', $id)->lockForUpdate() + ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts') + ->first(); + + $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$cp->id)->select('one_receive_number'); + + if (env('SUB_CHANNEL') == 1) { + $couponReceiveType->where('receive_type',$receiveType); + } + // 查询一次能领取的数量 + $crt = $couponReceiveType->first(); + + $cr = new CouponRec; + $cr->user_id = $userId; + $cr->system_coupon_user_id = $cp->id; + $cr->order_main_id = 0; + $cr->receive_time = $now; + $cr->number = $crt->one_receive_number; + $cr->number_remain = $crt->one_receive_number; + $cr->status = 0; + $cr->update_time = $now; + $cr->receive_type = $receiveType; + $cr->send_user_id = $sendUserId; + $cr->phone = $phone; + + //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内, 则返回领取失败的优惠券 + if ( + $cp->status != 1 + || + $cp->inventory <= $cp->inventory_use + || + $cp->inventory < ($cp->inventory_use+$cr->number) + || + $cp->start_time > $now + || + $cp->end_time < $now + ) + { + $result['status'] = 2; + $result['coupon_text'] = '红包已经领完~'; + + $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完'; + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + }else{ + // 判断是否领取过 存在记录则领取过 + $isReceive = CouponRec::select('id') + ->where('system_coupon_user_id',$id) + ->where('user_id',$userId) + ->exists(); + + if(!$isReceive){ + + $cp->inventory_use += $cr->number;//记录已领取的数量 + + if ( $cr->save() && $cp->save() ) { + $result['status'] = 0; + // $result['data'] = $cp; + $result['coupon_text'] = $cp['discounts'].'元红包'; + } + }else{ + $errorData['msg'] = '用户已经领取了此优惠券'; + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + } + } + } catch (Exception $e){ + $errorData['msg'] = $e->getMessage(); + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + } + }); + + return $result; + } +} \ No newline at end of file diff --git a/app/Service/CouponRebateServiceInterface.php b/app/Service/CouponRebateServiceInterface.php new file mode 100644 index 0000000..1ba93d0 --- /dev/null +++ b/app/Service/CouponRebateServiceInterface.php @@ -0,0 +1,11 @@ + Date: Wed, 5 Aug 2020 15:34:32 +0800 Subject: [PATCH 046/172] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E4=BC=98=E6=83=A0?= =?UTF-8?q?=E5=88=B8=E8=BF=94=E5=88=B8=E6=B6=88=E6=81=AF=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 28 ++++++++++++++++++ config/autoload/amqp.php | 33 ++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 app/Amqp/Consumer/couponRebateConsumer.php create mode 100644 config/autoload/amqp.php diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php new file mode 100644 index 0000000..7b04668 --- /dev/null +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -0,0 +1,28 @@ +getBody()); + return Result::ACK; + } + + public function isEnable(): bool + { + return parent::isEnable(); + } +} diff --git a/config/autoload/amqp.php b/config/autoload/amqp.php new file mode 100644 index 0000000..e14780a --- /dev/null +++ b/config/autoload/amqp.php @@ -0,0 +1,33 @@ + [ + 'host' => env('RQM_HOST', 'localhost'), + 'port' => 5672, + 'user' => env('RQM_USER','guest'), + 'password' => env('RQM_PASSWORD','guest'), + 'vhost' => '/', + 'concurrent' => [ + 'limit' => 1, + ], + 'pool' => [ + 'min_connections' => 1, + 'max_connections' => 10, + 'connect_timeout' => 10.0, + 'wait_timeout' => 3.0, + 'heartbeat' => -1, + ], + 'params' => [ + 'insist' => false, + 'login_method' => 'AMQPLAIN', + 'login_response' => null, + 'locale' => 'en_US', + 'connection_timeout' => 3.0, + 'read_write_timeout' => 6.0, + 'context' => null, + 'keepalive' => false, + 'heartbeat' => 3, + 'close_on_destruct' => false, + ], + ] +]; From 765dbccf8fa6465380e48a6ff2428b246a73f7f5 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 5 Aug 2020 15:41:08 +0800 Subject: [PATCH 047/172] =?UTF-8?q?=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index 7b04668..a4f7e27 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -18,6 +18,9 @@ class couponRebateConsumer extends ConsumerMessage { var_dump($data); var_dump($message->getBody()); + if (false) { + return Result::REQUEUE; + } return Result::ACK; } From 3481ead47977cfa9986d5126ae8d957978111c4a Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Wed, 5 Aug 2020 17:18:53 +0800 Subject: [PATCH 048/172] =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E7=BB=9F=E4=B8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 11 ++----- app/Service/CouponRebate.php | 28 ------------------ app/Service/CouponRebateService.php | 31 ++++++++++++++++++++ app/Service/CouponRebateServiceInterface.php | 5 ++++ config/autoload/dependencies.php | 2 +- 5 files changed, 40 insertions(+), 37 deletions(-) diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 43a73e9..c1b2b93 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -14,7 +14,7 @@ namespace App\Controller; use Hyperf\DbConnection\Db; use Hyperf\Redis\Redis; use Hyperf\Utils\ApplicationContext; -use App\Service\CouponRebateInterface; +use App\Service\CouponRebateServiceInterface; use http\Client\Curl\User; use Hyperf\Di\Annotation\Inject; use App\Model\Coupon; @@ -24,11 +24,6 @@ use App\Request\CouponRebateReceiveRequest; use App\Service\CouponRebateService; class CouponRebateController extends BaseController { - /** - * @Inject - * @var CouponRebateInterface - */ - protected $CouponRebate; /** * @Inject @@ -42,7 +37,7 @@ class CouponRebateController extends BaseController public function isCouponRebate() { $user_id = $this->request->input('user_id', 0); - $res = $this->CouponRebate->isCouponRebate($user_id); + $res = $this->CouponRebateService->isCouponRebate($user_id); return $this->success($res); } @@ -51,7 +46,7 @@ class CouponRebateController extends BaseController */ public function getActiveInfo() { - $res = $this->CouponRebate->getActiveInfo(); + $res = $this->CouponRebateService->getActiveInfo(); return $this->success($res); } diff --git a/app/Service/CouponRebate.php b/app/Service/CouponRebate.php index 9f05999..1afe901 100644 --- a/app/Service/CouponRebate.php +++ b/app/Service/CouponRebate.php @@ -10,34 +10,6 @@ use Hyperf\Paginator\Paginator; class CouponRebate implements CouponRebateInterface { - public function isCouponRebate($user_id) - { - $res = Db::table('ims_system_coupon_user as u') - ->leftjoin('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id') - ->where([ - ['r.user_id','=',$user_id], - ['r.receive_type','=',4], - ['u.active_type','=',2], - ]) - ->select('r.id') - ->first(); - return $res; - } - public function getActiveInfo() - { - $time = time(); - $res = Db::table('ims_system_coupon_user') - ->where([ - ['status','=',1], - ['active_type','=',2], - ['start_time','<=',$time], - ['end_time','>',$time], - ]) - ->whereRaw('inventory > inventory_use') - ->orderBy('addtime','desc') - ->get(); - return $res; - } } \ No newline at end of file diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index cdd384c..9db3bc9 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -132,4 +132,35 @@ class CouponRebateService implements CouponRebateServiceInterface return $result; } + + public function isCouponRebate($user_id) + { + $res = Db::table('ims_system_coupon_user as u') + ->leftjoin('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id') + ->where([ + ['r.user_id','=',$user_id], + ['r.receive_type','=',4], + ['u.active_type','=',2], + ]) + ->select('r.id') + ->first(); + return $res; + } + + public function getActiveInfo() + { + $time = time(); + $res = Db::table('ims_system_coupon_user') + ->where([ + ['status','=',1], + ['active_type','=',2], + ['start_time','<=',$time], + ['end_time','>',$time], + ]) + ->whereRaw('inventory > inventory_use') + ->orderBy('addtime','desc') + ->get(); + return $res; + } + } \ No newline at end of file diff --git a/app/Service/CouponRebateServiceInterface.php b/app/Service/CouponRebateServiceInterface.php index 1ba93d0..cc8c0ef 100644 --- a/app/Service/CouponRebateServiceInterface.php +++ b/app/Service/CouponRebateServiceInterface.php @@ -8,4 +8,9 @@ interface CouponRebateServiceInterface * 领取优惠券 */ public function userReceiveCoupon($params); + + public function isCouponRebate($user_id); + + public function getActiveInfo(); + } \ No newline at end of file diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 9089d7f..12dd53c 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -15,5 +15,5 @@ return [ \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, \App\Service\AdServiceInterface::class => \App\Service\AdService::class, \App\Commons\Log::class => \App\Commons\Log::class, - \App\Service\CouponRebateInterface::class => \App\Service\CouponRebate::class, + \App\Service\CouponRebateServiceInterface::class => \App\Service\CouponRebateService::class, ]; From 8406b27bca10533077335fa65d190e0f56925bdc Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Wed, 5 Aug 2020 17:22:25 +0800 Subject: [PATCH 049/172] =?UTF-8?q?=E5=90=88=E5=B9=B6=E5=90=8E=20=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E5=A4=9A=E4=BD=99=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebate.php | 15 --------------- app/Service/CouponRebateInterface.php | 12 ------------ 2 files changed, 27 deletions(-) delete mode 100644 app/Service/CouponRebate.php delete mode 100644 app/Service/CouponRebateInterface.php diff --git a/app/Service/CouponRebate.php b/app/Service/CouponRebate.php deleted file mode 100644 index 1afe901..0000000 --- a/app/Service/CouponRebate.php +++ /dev/null @@ -1,15 +0,0 @@ - Date: Wed, 5 Aug 2020 17:23:59 +0800 Subject: [PATCH 050/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E9=A2=86=E5=8F=96=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=EF=BC=8C=E4=B8=80=E6=AC=A1=E5=8F=AF=E9=A2=86=E5=8F=96?= =?UTF-8?q?=E5=A4=9A=E5=BC=A0=E4=BC=98=E6=83=A0=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Request/CouponRebateReceiveRequest.php | 6 +- app/Service/CouponRebateService.php | 171 +++++++++++---------- 2 files changed, 97 insertions(+), 80 deletions(-) diff --git a/app/Request/CouponRebateReceiveRequest.php b/app/Request/CouponRebateReceiveRequest.php index 3169c3e..4c4beed 100644 --- a/app/Request/CouponRebateReceiveRequest.php +++ b/app/Request/CouponRebateReceiveRequest.php @@ -24,7 +24,7 @@ class CouponRebateReceiveRequest extends FormRequest return [ 'user_id' => 'required|nonempty|integer|exists_enable:ims_cjdc_user,id', 'receive_type' => 'required|nonempty|integer', - 'id' => 'required|nonempty', + 'ids' => 'required|nonempty', ]; } @@ -33,7 +33,7 @@ class CouponRebateReceiveRequest extends FormRequest return [ 'user_id.*' => ':attribute信息不正确', 'receive_type.*' => ':attribute必须', - 'id.*' => ':attribute必须', + 'ids.*' => ':attribute必须', ]; } @@ -42,7 +42,7 @@ class CouponRebateReceiveRequest extends FormRequest return [ 'user_id' => '领取用户ID', 'receive_type' => '领取方式', - 'id' => '优惠券', + 'ids' => '优惠券', ]; } } diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index cdd384c..e0f9007 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -21,113 +21,130 @@ class CouponRebateService implements CouponRebateServiceInterface /** * 领取优惠券 + * 返券活动领取 + * 一次可领取多张优惠券 + * 一个用户不可重复领取 */ public function userReceiveCoupon($params) { $userId = $params["user_id"]; $receiveType = $params["receive_type"]; - $id = $params["id"]; + $ids = $params["ids"]; $sendUserId = $params["send_user_id"]; $phone = $params["phone"]; $now = time(); + $ids = is_array($ids) ? implode(',',$ids) : $ids; - // status : 0 领取成功 >0 领取失败 + // status: 0领取成功 >0领取失败 $result = [ 'status' => 1, - 'data' => [], 'coupon_text' => '继续努力~' ]; // 错误日志记录 $errorData = [ - 'coupon_id' =>$id, + 'coupon_ids' =>$ids, 'user_id' =>$userId, 'receiveType' =>$receiveType, 'sendUserId' =>$sendUserId, 'phone' =>$phone ]; - Db::transaction( function() use ($id,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData) { + Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData) { - try{ - //读写锁,完全控制,性能低 - $cp = Coupon::where('id', $id)->lockForUpdate() - ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts') - ->first(); - - $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$cp->id)->select('one_receive_number'); + try{ + //读写锁,完全控制,性能低 + $coupons = Coupon::whereIn('id', $ids)->lockForUpdate() + ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts') + ->get(); - if (env('SUB_CHANNEL') == 1) { - $couponReceiveType->where('receive_type',$receiveType); - } - // 查询一次能领取的数量 - $crt = $couponReceiveType->first(); - - $cr = new CouponRec; - $cr->user_id = $userId; - $cr->system_coupon_user_id = $cp->id; - $cr->order_main_id = 0; - $cr->receive_time = $now; - $cr->number = $crt->one_receive_number; - $cr->number_remain = $crt->one_receive_number; - $cr->status = 0; - $cr->update_time = $now; - $cr->receive_type = $receiveType; - $cr->send_user_id = $sendUserId; - $cr->phone = $phone; - - //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内, 则返回领取失败的优惠券 - if ( - $cp->status != 1 - || - $cp->inventory <= $cp->inventory_use - || - $cp->inventory < ($cp->inventory_use+$cr->number) - || - $cp->start_time > $now - || - $cp->end_time < $now - ) - { - $result['status'] = 2; - $result['coupon_text'] = '红包已经领完~'; + foreach($coupons as $coupon){ + $errorData['coupon_id'] = $coupon->id; - $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完'; - $this->log->event( - LogLabel::COUPON_LOG, - $errorData - ); - }else{ - // 判断是否领取过 存在记录则领取过 - $isReceive = CouponRec::select('id') - ->where('system_coupon_user_id',$id) - ->where('user_id',$userId) - ->exists(); + //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内可领取, 否则返回领取失败的优惠券 + if ( + $coupon->status == 1 + && + $coupon->inventory > $coupon->inventory_use + && + $coupon->start_time <= $now + && + $coupon->end_time >= $now + ) + { - if(!$isReceive){ + // 查询一次能领取的数量 + $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number'); + if (env('SUB_CHANNEL') == 1) { + $couponReceiveType->where('receive_type',$receiveType); + } + $couponReceiveType = $couponReceiveType->first(); + + // 优惠券可领取数量 >= 本次领取数量 + if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){ - $cp->inventory_use += $cr->number;//记录已领取的数量 - - if ( $cr->save() && $cp->save() ) { - $result['status'] = 0; - // $result['data'] = $cp; - $result['coupon_text'] = $cp['discounts'].'元红包'; + // 判断是否领取过 存在记录则领取过 + $isReceive = CouponRec::select('id') + ->where('system_coupon_user_id',$ids) + ->where('user_id',$userId) + ->exists(); + + if(!$isReceive){ + //记录已领取的数量 + $coupon->inventory_use += $couponReceiveType->number; + + $couponReceive = new CouponRec; + $couponReceive->user_id = $userId; + $couponReceive->system_coupon_user_id = $coupon->id; + $couponReceive->order_main_id = 0; + $couponReceive->receive_time = $now; + $couponReceive->number = $couponReceiveType->one_receive_number; + $couponReceive->number_remain = $couponReceiveType->one_receive_number; + $couponReceive->status = 0; + $couponReceive->update_time = $now; + $couponReceive->receive_type = $receiveType; + $couponReceive->send_user_id = $sendUserId; + $couponReceive->phone = $phone; + + if ( $couponReceive->save() && $coupon->save() ) { + $result['status'] = 0; + $result['coupon_text'] = '恭喜您领取成功!'; + } + }else{ + $result['status'] = 2; + $result['coupon_text'] = '您已领取!赶快去下单吧~'; + + $errorData['msg'] = '用户已经领取了优惠券'; + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + } + }else{ + $errorData['remain_receive_number'] = $coupon->inventory - $coupon->inventory_use; + $errorData['one_receive_number'] = $couponReceiveType->one_receive_number; + $errorData['msg'] = '优惠券剩余数量不足'; + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + } + }else{ + $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完'; + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); } - }else{ - $errorData['msg'] = '用户已经领取了此优惠券'; - $this->log->event( - LogLabel::COUPON_LOG, - $errorData - ); } + + } catch (Exception $e){ + $errorData['msg'] = $e->getMessage(); + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); } - } catch (Exception $e){ - $errorData['msg'] = $e->getMessage(); - $this->log->event( - LogLabel::COUPON_LOG, - $errorData - ); - } }); return $result; From 8e004f23c774b1fabc087dfd116812532e3a416f Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Wed, 5 Aug 2020 21:04:52 +0800 Subject: [PATCH 051/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8-=E9=A2=86=E5=8F=96=E6=88=90?= =?UTF-8?q?=E5=8A=9F=E8=AE=B0=E5=BD=95=E5=88=B0ssdb?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/SsdbKeysPrefix.php | 5 +++ app/Service/CouponRebateService.php | 57 ++++++++++++++++++++++------- 2 files changed, 49 insertions(+), 13 deletions(-) diff --git a/app/Constants/SsdbKeysPrefix.php b/app/Constants/SsdbKeysPrefix.php index 158fefe..2cac620 100644 --- a/app/Constants/SsdbKeysPrefix.php +++ b/app/Constants/SsdbKeysPrefix.php @@ -16,4 +16,9 @@ class SsdbKeysPrefix extends AbstractConstants * @Message("Params Token Key Prefix") */ const PARAMS_TOKEN = 'params_token_'; + + /** + * @Message("Coupon rebate Key Prefix") + */ + const COUPON_REBATE_RECEIVE = 'coupon_rebate_receive_'; } diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 19d077f..7c06421 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -9,6 +9,9 @@ use App\Model\CouponUserRecType; use App\Model\CouponRec; use App\Constants\LogLabel; use App\Commons\Log; +use Hyperf\Utils\ApplicationContext; +use App\TaskWorker\SSDBTask; +use App\Constants\SsdbKeysPrefix; use Exception; class CouponRebateService implements CouponRebateServiceInterface @@ -40,7 +43,7 @@ class CouponRebateService implements CouponRebateServiceInterface 'status' => 1, 'coupon_text' => '继续努力~' ]; - + // 错误日志记录 $errorData = [ 'coupon_ids' =>$ids, @@ -50,12 +53,17 @@ class CouponRebateService implements CouponRebateServiceInterface 'phone' =>$phone ]; - Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData) { + $receiveSsdb = []; + + try{ + Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData,&$receiveSsdb) { - try{ + $success = []; + $fail = []; + //读写锁,完全控制,性能低 $coupons = Coupon::whereIn('id', $ids)->lockForUpdate() - ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts') + ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts','active_type') ->get(); foreach($coupons as $coupon){ @@ -70,6 +78,8 @@ class CouponRebateService implements CouponRebateServiceInterface $coupon->start_time <= $now && $coupon->end_time >= $now + && + $coupon->active_type == 2 ) { @@ -107,10 +117,12 @@ class CouponRebateService implements CouponRebateServiceInterface $couponReceive->phone = $phone; if ( $couponReceive->save() && $coupon->save() ) { - $result['status'] = 0; - $result['coupon_text'] = '恭喜您领取成功!'; + $success[] = $coupon; + $receiveSsdb[] = $coupon->id;; } }else{ + $fail[] = $coupon; + $receiveSsdb[] = $coupon->id; $result['status'] = 2; $result['coupon_text'] = '您已领取!赶快去下单吧~'; @@ -121,6 +133,7 @@ class CouponRebateService implements CouponRebateServiceInterface ); } }else{ + $fail[] = $coupon; $errorData['remain_receive_number'] = $coupon->inventory - $coupon->inventory_use; $errorData['one_receive_number'] = $couponReceiveType->one_receive_number; $errorData['msg'] = '优惠券剩余数量不足'; @@ -130,6 +143,7 @@ class CouponRebateService implements CouponRebateServiceInterface ); } }else{ + $fail[] = $coupon; $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完'; $this->log->event( LogLabel::COUPON_LOG, @@ -137,16 +151,33 @@ class CouponRebateService implements CouponRebateServiceInterface ); } } - - } catch (Exception $e){ - $errorData['msg'] = $e->getMessage(); + $result['data'] = [ + 'success' => $success, + 'fail' => $fail + ]; + if(count($success) > 0){ + $result['status'] = 0; + $result['coupon_text'] = '恭喜您领取成功!'; + } + }); + } catch (Exception $e){ + $errorData['msg'] = $e->getMessage(); + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + } + if(count($receiveSsdb) > 0){ + // 记录到ssdb + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + if(false === $ssdb->exec('hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE.$userId,$receiveSsdb)){ + $errorData['msg'] = '记录领取优惠券到ssdb失败'; $this->log->event( LogLabel::COUPON_LOG, $errorData - ); - } - }); - + ); + }; + } return $result; } From 1ddf72a15fdbf0b36f2624c114dba1421877cb0d Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Wed, 5 Aug 2020 21:28:48 +0800 Subject: [PATCH 052/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E9=A2=86?= =?UTF-8?q?=E5=8F=96=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 7c06421..6d488c1 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -36,7 +36,7 @@ class CouponRebateService implements CouponRebateServiceInterface $sendUserId = $params["send_user_id"]; $phone = $params["phone"]; $now = time(); - $ids = is_array($ids) ? implode(',',$ids) : $ids; + $ids = is_array($ids) ? $ids : explode(',',$ids); // status: 0领取成功 >0领取失败 $result = [ @@ -60,9 +60,10 @@ class CouponRebateService implements CouponRebateServiceInterface $success = []; $fail = []; + $isr = []; //读写锁,完全控制,性能低 - $coupons = Coupon::whereIn('id', $ids)->lockForUpdate() + $coupons = Coupon::whereIn('id', $ids)->lockForUpdate() ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts','active_type') ->get(); @@ -95,7 +96,7 @@ class CouponRebateService implements CouponRebateServiceInterface // 判断是否领取过 存在记录则领取过 $isReceive = CouponRec::select('id') - ->where('system_coupon_user_id',$ids) + ->where('system_coupon_user_id',$coupon->id) ->where('user_id',$userId) ->exists(); @@ -116,10 +117,10 @@ class CouponRebateService implements CouponRebateServiceInterface $couponReceive->send_user_id = $sendUserId; $couponReceive->phone = $phone; - if ( $couponReceive->save() && $coupon->save() ) { - $success[] = $coupon; - $receiveSsdb[] = $coupon->id;; - } + // if ( $couponReceive->save() && $coupon->save() ) { + // $success[] = $coupon; + // $receiveSsdb[] = $coupon->id;; + // } }else{ $fail[] = $coupon; $receiveSsdb[] = $coupon->id; @@ -168,9 +169,14 @@ class CouponRebateService implements CouponRebateServiceInterface ); } if(count($receiveSsdb) > 0){ + $saveSsdb = []; + foreach($receiveSsdb as $kssdb => $vssdb){ + $saveSsdb[] = $kssdb; + $saveSsdb[] = $vssdb; + } // 记录到ssdb $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - if(false === $ssdb->exec('hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE.$userId,$receiveSsdb)){ + if(false === $ssdb->exec('hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE.$userId,$saveSsdb)){ $errorData['msg'] = '记录领取优惠券到ssdb失败'; $this->log->event( LogLabel::COUPON_LOG, From 4d79a99ad0b56eed1359bae1c37cfb75d063d4c3 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Thu, 6 Aug 2020 10:24:02 +0800 Subject: [PATCH 053/172] =?UTF-8?q?=E8=BF=94=E5=88=B8=E6=B4=BB=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 11 + app/Controller/CouponRebateController.php | 16 +- app/Service/CouponRebateService.php | 248 +++++++++++++------ app/Service/CouponRebateServiceInterface.php | 2 + config/routes.php | 1 + 5 files changed, 196 insertions(+), 82 deletions(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index a4f7e27..475c7b9 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -8,16 +8,27 @@ use Hyperf\Amqp\Result; use Hyperf\Amqp\Annotation\Consumer; use Hyperf\Amqp\Message\ConsumerMessage; use PhpAmqpLib\Message\AMQPMessage; +use App\Service\CouponRebateService; +use App\Service\CouponRebateServiceInterface; +use Hyperf\Di\Annotation\Inject; /** * @Consumer(exchange="couponRebate", routingKey="couponRebate", queue="couponRebate", name ="couponRebateConsumer", nums=1) */ class couponRebateConsumer extends ConsumerMessage { + /** + * @Inject + * @var CouponRebateService + */ + protected $CouponRebateService; + public function consumeMessage($data, AMQPMessage $message): string { var_dump($data); var_dump($message->getBody()); + $res = $this->CouponRebateService->couponRebate($data); + var_dump($res); if (false) { return Result::REQUEUE; } diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index c1b2b93..30cc5bb 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -25,11 +25,11 @@ use App\Service\CouponRebateService; class CouponRebateController extends BaseController { - /** + /** * @Inject * @var CouponRebateService */ - protected $CouponRebateService; + protected $CouponRebateService; /** * 用户是否领取过领取优惠券 @@ -50,13 +50,21 @@ class CouponRebateController extends BaseController return $this->success($res); } - + /** * 用户领取优惠券 * 2020.08.04 只领一张优惠券 - */ + */ public function userReceiveCoupon(CouponRebateReceiveRequest $validator) { return $this->success($this->CouponRebateService->userReceiveCoupon($this->request->all())); } + + public function couponRebate() + { + $order_id = $this->request->input('order_id', 0); + $res = $this->CouponRebateService->couponRebate($order_id); + return $this->success($res); + } + } diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 9db3bc9..48d8596 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -13,7 +13,7 @@ use Exception; class CouponRebateService implements CouponRebateServiceInterface { - /** + /** * @Inject * @var Log */ @@ -30,7 +30,7 @@ class CouponRebateService implements CouponRebateServiceInterface $sendUserId = $params["send_user_id"]; $phone = $params["phone"]; $now = time(); - + // status : 0 领取成功 >0 领取失败 $result = [ 'status' => 1, @@ -49,113 +49,119 @@ class CouponRebateService implements CouponRebateServiceInterface Db::transaction( function() use ($id,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData) { - try{ - //读写锁,完全控制,性能低 - $cp = Coupon::where('id', $id)->lockForUpdate() + try{ + //读写锁,完全控制,性能低 + $cp = Coupon::where('id', $id)->lockForUpdate() ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts') ->first(); - - $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$cp->id)->select('one_receive_number'); - if (env('SUB_CHANNEL') == 1) { - $couponReceiveType->where('receive_type',$receiveType); - } - // 查询一次能领取的数量 - $crt = $couponReceiveType->first(); - - $cr = new CouponRec; - $cr->user_id = $userId; - $cr->system_coupon_user_id = $cp->id; - $cr->order_main_id = 0; - $cr->receive_time = $now; - $cr->number = $crt->one_receive_number; - $cr->number_remain = $crt->one_receive_number; - $cr->status = 0; - $cr->update_time = $now; - $cr->receive_type = $receiveType; - $cr->send_user_id = $sendUserId; - $cr->phone = $phone; - - //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内, 则返回领取失败的优惠券 - if ( - $cp->status != 1 - || - $cp->inventory <= $cp->inventory_use - || - $cp->inventory < ($cp->inventory_use+$cr->number) - || - $cp->start_time > $now - || - $cp->end_time < $now + $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$cp->id)->select('one_receive_number'); + + if (env('SUB_CHANNEL') == 1) { + $couponReceiveType->where('receive_type',$receiveType); + } + // 查询一次能领取的数量 + $crt = $couponReceiveType->first(); + + $cr = new CouponRec; + $cr->user_id = $userId; + $cr->system_coupon_user_id = $cp->id; + $cr->order_main_id = 0; + $cr->receive_time = $now; + $cr->number = $crt->one_receive_number; + $cr->number_remain = $crt->one_receive_number; + $cr->status = 0; + $cr->update_time = $now; + $cr->receive_type = $receiveType; + $cr->send_user_id = $sendUserId; + $cr->phone = $phone; + + //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内, 则返回领取失败的优惠券 + if ( + $cp->status != 1 + || + $cp->inventory <= $cp->inventory_use + || + $cp->inventory < ($cp->inventory_use+$cr->number) + || + $cp->start_time > $now + || + $cp->end_time < $now ) - { - $result['status'] = 2; - $result['coupon_text'] = '红包已经领完~'; + { + $result['status'] = 2; + $result['coupon_text'] = '红包已经领完~'; - $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完'; - $this->log->event( - LogLabel::COUPON_LOG, - $errorData - ); - }else{ - // 判断是否领取过 存在记录则领取过 - $isReceive = CouponRec::select('id') - ->where('system_coupon_user_id',$id) - ->where('user_id',$userId) - ->exists(); - - if(!$isReceive){ - - $cp->inventory_use += $cr->number;//记录已领取的数量 - - if ( $cr->save() && $cp->save() ) { - $result['status'] = 0; - // $result['data'] = $cp; - $result['coupon_text'] = $cp['discounts'].'元红包'; - } - }else{ - $errorData['msg'] = '用户已经领取了此优惠券'; + $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完'; $this->log->event( LogLabel::COUPON_LOG, $errorData - ); + ); + }else{ + // 判断是否领取过 存在记录则领取过 + $isReceive = CouponRec::select('id') + ->where('system_coupon_user_id',$id) + ->where('user_id',$userId) + ->exists(); + + if(!$isReceive){ + + $cp->inventory_use += $cr->number;//记录已领取的数量 + + if ( $cr->save() && $cp->save() ) { + $result['status'] = 0; + // $result['data'] = $cp; + $result['coupon_text'] = $cp['discounts'].'元红包'; + } + }else{ + $errorData['msg'] = '用户已经领取了此优惠券'; + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + } } + } catch (Exception $e){ + $errorData['msg'] = $e->getMessage(); + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); } - } catch (Exception $e){ - $errorData['msg'] = $e->getMessage(); - $this->log->event( - LogLabel::COUPON_LOG, - $errorData - ); - } }); return $result; } + /* + * 判断用户是否已领取过优惠券 + * */ public function isCouponRebate($user_id) { $res = Db::table('ims_system_coupon_user as u') ->leftjoin('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id') ->where([ - ['r.user_id','=',$user_id], - ['r.receive_type','=',4], - ['u.active_type','=',2], + ['r.user_id' ,'=', $user_id], + ['r.receive_type','=', 4], + ['u.active_type' ,'=', 2], ]) ->select('r.id') ->first(); return $res; } + /* + *获取活动信息 + */ public function getActiveInfo() { $time = time(); $res = Db::table('ims_system_coupon_user') ->where([ - ['status','=',1], - ['active_type','=',2], - ['start_time','<=',$time], - ['end_time','>',$time], + ['status' ,'=', 1], + ['active_type' ,'=', 2], + ['start_time' ,'<=', $time], + ['end_time' ,'>', $time], ]) ->whereRaw('inventory > inventory_use') ->orderBy('addtime','desc') @@ -163,4 +169,90 @@ class CouponRebateService implements CouponRebateServiceInterface return $res; } + /* + * 支付成功 返券 + */ + public function couponRebate($order_id) + { + + /* 判断优惠券类型是否为转发活动优惠券 */ + $coupon = Db::table('ims_system_coupon_user_receive as r') + ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id') + ->where([ + ['u.order_main_id', '=', $order_id], + ['r.send_user_id', '>', 0], + ['r.rebate_type', '=', 1], + ['r.receive_type', '=', 4], + ['u.status', '=', 1], + ]) + ->select('r.id', 'r.send_user_id', 'u.system_coupon_id') + ->first(); + /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/ + if (isset($coupon->send_user_id) && ($coupon->send_user_id) > 0) { + //判断该优惠券是否有库存 +// $inventory = Db::table('system_coupon_user_receive as r'); +// if($inventory['inventory'] <= 0){ +// return '库存不足'; +// } + //判断用户是否已有该类型优惠券 + $exist_coupon = Db::table('ims_system_coupon_user_receive') + ->where([ + ['system_coupon_user_id', '=', $coupon->system_coupon_id], + ['user_id', '=', $coupon->send_user_id], + ['receive_type', '=', 5], + ['status', '=', 0], + ]) + ->select('id') + ->first(); + //return $exist_coupon; + //开启事务 + try { + /* + * 如果已有该优惠券 则领取数量 和 可用数量 自增1 + * 否则新增一条返券记录 + */ + $nowTime = time(); + $res = Db::table('ims_system_coupon_user_receive')->updateOrInsert( + [ + 'system_coupon_user_id' => $coupon->system_coupon_id, + 'user_id' => $coupon->send_user_id, + 'receive_type' => 5, + 'status' => 0, + ], + [ + 'order_main_id' => $order_id, + 'receive_time' => $nowTime, + 'number' => 1, + 'number_remain' => 1, + 'update_time' => $nowTime, + 'created_at' => $nowTime, + 'updated_at' => $nowTime, + ] + ); +// if ($res) { +// //首次返券更新rebate_type字段 防止重复返券 +// Db::table('system_coupon_user_receive')->where('id', $coupon->id)->update(['rebate_type' => 2]); +// //更新库存操作 +// Db::table('system_coupon_user') +// ->where('id', $coupon->id) +// ->increment('inventory_use'); +// } else { +// Db::rollBack(); +// return '事务失败'; +// } + // 提交 + Db::commit(); + } catch (\Exception $e) { + // 回滚 + Db::rollBack(); + return '返券失败'; + } + } else { +// $str1 = 'order_main_id:'.$this->order_id . ',未查询到用户领取优惠券信息['.$coupon.']'; +// $this->couponErrorLog($str1); + } + + + return $exist_coupon->id; + } } \ No newline at end of file diff --git a/app/Service/CouponRebateServiceInterface.php b/app/Service/CouponRebateServiceInterface.php index cc8c0ef..f7bc3a0 100644 --- a/app/Service/CouponRebateServiceInterface.php +++ b/app/Service/CouponRebateServiceInterface.php @@ -13,4 +13,6 @@ interface CouponRebateServiceInterface public function getActiveInfo(); + public function couponRebate($order_id); + } \ No newline at end of file diff --git a/config/routes.php b/config/routes.php index 0db0115..0f3633c 100644 --- a/config/routes.php +++ b/config/routes.php @@ -29,4 +29,5 @@ Router::addGroup('/v1/',function (){ Router::post('CouponRebate/isCouponRebate', 'App\Controller\CouponRebateController@isCouponRebate'); Router::post('CouponRebate/userReceiveCoupon', 'App\Controller\CouponRebateController@userReceiveCoupon'); Router::post('CouponRebate/getActiveInfo', 'App\Controller\CouponRebateController@getActiveInfo'); + Router::post('CouponRebate/couponRebate', 'App\Controller\CouponRebateController@couponRebate'); }); \ No newline at end of file From 240f58c43ef79907cd7696efe83d9f20fe4fe782 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Thu, 6 Aug 2020 11:35:42 +0800 Subject: [PATCH 054/172] =?UTF-8?q?=E8=87=AA=E5=A2=9E=E6=88=96=E6=8F=92?= =?UTF-8?q?=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 48d8596..78213ae 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -174,7 +174,6 @@ class CouponRebateService implements CouponRebateServiceInterface */ public function couponRebate($order_id) { - /* 判断优惠券类型是否为转发活动优惠券 */ $coupon = Db::table('ims_system_coupon_user_receive as r') ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id') @@ -212,7 +211,7 @@ class CouponRebateService implements CouponRebateServiceInterface * 否则新增一条返券记录 */ $nowTime = time(); - $res = Db::table('ims_system_coupon_user_receive')->updateOrInsert( + $res = Db::table('ims_system_coupon_user_receive')->updateOrIncrement( [ 'system_coupon_user_id' => $coupon->system_coupon_id, 'user_id' => $coupon->send_user_id, @@ -222,11 +221,13 @@ class CouponRebateService implements CouponRebateServiceInterface [ 'order_main_id' => $order_id, 'receive_time' => $nowTime, - 'number' => 1, - 'number_remain' => 1, 'update_time' => $nowTime, 'created_at' => $nowTime, 'updated_at' => $nowTime, + ], + [ + 'number' => 1, + 'number_remain' => 1, ] ); // if ($res) { From c715d1e81fc02cf99a408b9bed84a0c5bb28ba4b Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Thu, 6 Aug 2020 15:06:58 +0800 Subject: [PATCH 055/172] =?UTF-8?q?=E6=89=B9=E9=87=8F=E8=87=AA=E5=A2=9Eor?= =?UTF-8?q?=E6=8F=92=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 78213ae..af734c0 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -193,16 +193,6 @@ class CouponRebateService implements CouponRebateServiceInterface // if($inventory['inventory'] <= 0){ // return '库存不足'; // } - //判断用户是否已有该类型优惠券 - $exist_coupon = Db::table('ims_system_coupon_user_receive') - ->where([ - ['system_coupon_user_id', '=', $coupon->system_coupon_id], - ['user_id', '=', $coupon->send_user_id], - ['receive_type', '=', 5], - ['status', '=', 0], - ]) - ->select('id') - ->first(); //return $exist_coupon; //开启事务 try { @@ -211,7 +201,7 @@ class CouponRebateService implements CouponRebateServiceInterface * 否则新增一条返券记录 */ $nowTime = time(); - $res = Db::table('ims_system_coupon_user_receive')->updateOrIncrement( + $res = Db::table('ims_system_coupon_user_receive')->moreIncrementOrInsert( [ 'system_coupon_user_id' => $coupon->system_coupon_id, 'user_id' => $coupon->send_user_id, @@ -254,6 +244,6 @@ class CouponRebateService implements CouponRebateServiceInterface } - return $exist_coupon->id; + return '返券成功'; } } \ No newline at end of file From e0ed0eca9657d3529ca8728301fc191bd568a26a Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Thu, 6 Aug 2020 15:07:47 +0800 Subject: [PATCH 056/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E5=8F=AF?= =?UTF-8?q?=E9=A2=86=E5=8F=96=E4=BC=98=E6=83=A0=E5=88=B8=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?getSystemCouponUserList=EF=BC=8C=E5=A2=9E=E5=8A=A0=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E7=BB=91=E5=AE=9A=E4=BC=98=E6=83=A0=E5=88=B8=E6=B4=BB?= =?UTF-8?q?=E5=8A=A8=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/SsdbKeysPrefix.php | 10 ++ app/Controller/CouponController.php | 79 ++--------- app/Controller/CouponRebateController.php | 15 +- app/Request/CouponGetListRequest.php | 45 ++++++ app/Request/CouponRebateTieRequest.php | 48 +++++++ app/Service/CouponRebateService.php | 54 ++++++- app/Service/CouponRebateServiceInterface.php | 2 + app/Service/CouponService.php | 141 +++++++++++++++++++ app/Service/CouponServiceInterface.php | 18 +++ config/routes.php | 1 + 10 files changed, 345 insertions(+), 68 deletions(-) create mode 100644 app/Request/CouponGetListRequest.php create mode 100644 app/Request/CouponRebateTieRequest.php create mode 100644 app/Service/CouponService.php create mode 100644 app/Service/CouponServiceInterface.php diff --git a/app/Constants/SsdbKeysPrefix.php b/app/Constants/SsdbKeysPrefix.php index 2cac620..2550f84 100644 --- a/app/Constants/SsdbKeysPrefix.php +++ b/app/Constants/SsdbKeysPrefix.php @@ -21,4 +21,14 @@ class SsdbKeysPrefix extends AbstractConstants * @Message("Coupon rebate Key Prefix") */ const COUPON_REBATE_RECEIVE = 'coupon_rebate_receive_'; + + /** + * @Message("Coupon rebate Key Prefix") + */ + const COUPON_REBATE_FORWARD = 'coupon_rebate_forward_'; + + /** + * @Message("Coupon rebate Key Prefix") + */ + const COUPON_REBATE_REPAY = 'coupon_rebate_REPAY_'; } diff --git a/app/Controller/CouponController.php b/app/Controller/CouponController.php index 5152e63..6212782 100644 --- a/app/Controller/CouponController.php +++ b/app/Controller/CouponController.php @@ -12,86 +12,33 @@ declare(strict_types=1); namespace App\Controller; +use Hyperf\Di\Annotation\Inject; use App\Model\CouponUserRecType; use App\Model\Coupon; use App\Model\CouponRec; use Hyperf\DbConnection\Db; use Hyperf\Redis\Redis; use Hyperf\Utils\ApplicationContext; +use App\Request\CouponGetListRequest; +use App\Service\CouponService; class CouponController extends BaseController { + /** + * @Inject + * @var CouponService + */ + protected $couponService; /** * 获取用户可领取优惠卷接口 */ - public function getSystemCouponUserList() + public function getSystemCouponUserList(CouponGetListRequest $validator) { - $user_id = $this->request->input('user_id', 0); - $receive_type = $this->request->input('receive_type', 0); - - if ($this->empty($user_id) || $this->empty($receive_type)) { - return $this->success(['not_reveive' => []]); - } - - $c_ids = []; - // 渠道开启,查询该渠道可以领取的优惠券ID - // 渠道未开启,查询所有优惠券 - if (env('SUB_CHANNEL') == 1) { - $c_ids = CouponUserRecType::where('receive_type', $receive_type)->pluck('system_coupon_user_id'); - } else { - $c_ids = Coupon::pluck('id'); - } - - $nowTime = time(); - - $where = [ - ['user_id',"=",$user_id] - ]; - - // 渠道开启,查询该用户在此渠道领过的优惠券ID - if (env('SUB_CHANNEL') == 1) { - array_push($where, ['receive_type', "=", $receive_type]); - } - - $cr_ids = CouponRec::where($where)->pluck('system_coupon_user_id'); - - //领过券的ID - $c_ids = $c_ids->toArray(); - $cr_ids = $cr_ids->toArray(); - - // 当前用户可领的优惠券ID - $couponIds = array_diff($c_ids, $cr_ids); - - $whereC = [ - ['u.end_time','>',$nowTime], - ['u.start_time','<=',$nowTime], - ['u.status','=',1], - ['u.active_type','=',1], - ]; - - if (env('SUB_CHANNEL') == 1) { - array_push($whereC, ['type.receive_type','=',$receive_type]); - } - - $c = Db::table('ims_system_coupon_user as u') - ->where($whereC) - ->join('ims_system_coupon_user_receivetype as type', 'u.id', '=', 'type.system_coupon_user_id') - ->whereRaw('u.inventory_use <= u.inventory and u.inventory-u.inventory_use > type.one_receive_number') - // ->whereIn('u.id',$c_ids) - // ->whereNotIn('u.id',$cr_ids) - ->whereIn('u.id', $couponIds) - ->select('u.*','type.one_receive_number') - ->orderBy('u.weigh','desc') - // ->orderByRaw('FIELD(u.id, '.implode(", " , $ids).')') - ->limit(4) - ->get(); - foreach ($c as $k => &$v){ - if($v->discount_type == 2){ - $v->discounts = floatval($v->discounts); - } - } - return $this->success(['not_reveive'=>$c]); + $userId = $this->request->input('user_id', 0); + $receiveType = $this->request->input('receive_type', 0); + $res = $this->couponService->getSystemCouponUserList($userId,$receiveType); + return $this->success($res); } //统计用户 diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index c1b2b93..41b8fdb 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -22,6 +22,7 @@ use App\Model\CouponUserRecType; use App\Model\CouponRec; use App\Request\CouponRebateReceiveRequest; use App\Service\CouponRebateService; +use App\Request\CouponRebateTieRequest; class CouponRebateController extends BaseController { @@ -53,10 +54,22 @@ class CouponRebateController extends BaseController /** * 用户领取优惠券 - * 2020.08.04 只领一张优惠券 */ public function userReceiveCoupon(CouponRebateReceiveRequest $validator) { return $this->success($this->CouponRebateService->userReceiveCoupon($this->request->all())); } + + /** + * 将优惠券绑定活动 + */ + public function tieCouponActive(CouponRebateTieRequest $validator) + { + $couponForward = $this->request->input('coupon_forward_ids',[]); + $couponForward = is_array($couponForward) ? $couponForward : explode(',',$couponForward) ; + $couponRepay = $this->request->input('coupon_repay_id',0); + $couponActivity = $this->request->input('coupon_activity',0); + $res = $this->CouponRebateService->tieCouponActive($couponActivity,$couponForward,$couponRepay); + return $this->success($res); + } } diff --git a/app/Request/CouponGetListRequest.php b/app/Request/CouponGetListRequest.php new file mode 100644 index 0000000..252a45c --- /dev/null +++ b/app/Request/CouponGetListRequest.php @@ -0,0 +1,45 @@ + 'required|nonempty|integer|exists_enable:ims_cjdc_user,id', + 'receive_type' => 'required|nonempty|integer' + ]; + } + + public function messages(): array + { + return [ + 'user_id.*' => ':attribute信息不正确', + 'receive_type.*' => ':attribute必须' + ]; + } + + public function attributes(): array + { + return [ + 'user_id' => '用户ID', + 'receive_type' => '领取方式' + ]; + } +} diff --git a/app/Request/CouponRebateTieRequest.php b/app/Request/CouponRebateTieRequest.php new file mode 100644 index 0000000..39a5863 --- /dev/null +++ b/app/Request/CouponRebateTieRequest.php @@ -0,0 +1,48 @@ + 'required|nonempty', + 'coupon_forward_ids' => 'required|nonempty', + 'coupon_repay_id' => 'required|nonempty', + ]; + } + + public function messages(): array + { + return [ + 'coupon_activity.*' => ':attribute必须', + 'coupon_forward_ids.*' => ':attribute必须', + 'coupon_repay_id.*' => ':attribute必须', + ]; + } + + public function attributes(): array + { + return [ + 'coupon_activity' => '优惠券活动', + 'coupon_forward_ids' => '领取类型优惠券', + 'coupon_repay_id' => '返还类型优惠券', + ]; + } +} diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 6d488c1..c7dad5b 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -176,7 +176,7 @@ class CouponRebateService implements CouponRebateServiceInterface } // 记录到ssdb $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - if(false === $ssdb->exec('hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE.$userId,$saveSsdb)){ + if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE.$userId,$saveSsdb)){ $errorData['msg'] = '记录领取优惠券到ssdb失败'; $this->log->event( LogLabel::COUPON_LOG, @@ -216,5 +216,57 @@ class CouponRebateService implements CouponRebateServiceInterface ->get(); return $res; } + + /** + * 将优惠券绑定活动 + * 领取优惠券 COUPON_REBATE_FORWARD 可多张 + * 返还优惠券 COUPON_REBATE_REPAY 只一张 + */ + public function tieCouponActive($couponActivity,$couponForward,$couponRepay) + { + $result = [ + 'forward' => true, + 'repay' => true, + ]; + + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $rrss1 = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_FORWARD.$couponActivity); + $rrss2 = $ssdb->exec('get',SsdbKeysPrefix::COUPON_REBATE_REPAY.$couponActivity); + return [$rrss1,$rrss2]; + // 记录领取类型优惠券 + $forwardData = []; + foreach($couponForward as $kForward => $vForward){ + $forwardData[] = $kForward; + $forwardData[] = $vForward; + } + + if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_FORWARD.$couponActivity,$forwardData)){ + + $this->log->event( + LogLabel::COUPON_LOG, + [ + 'coupon_activity' => $couponActivity, + 'coupon_forward' => $forwardData, + 'msg' => '绑定-领取-优惠券到ssdb失败' + ] + ); + $result['forward'] = false; + }; + + // 记录返还类型优惠券 + if(false === $ssdb->exec('set',SsdbKeysPrefix::COUPON_REBATE_REPAY.$couponActivity,$couponRepay)){ + + $this->log->event( + LogLabel::COUPON_LOG, + [ + 'coupon_activity' => $couponActivity, + 'coupon_Repay' => $couponRepay, + 'msg' => '绑定-返还-优惠券到ssdb失败' + ] + ); + $result['repay'] = false; + }; + return $result; + } } \ No newline at end of file diff --git a/app/Service/CouponRebateServiceInterface.php b/app/Service/CouponRebateServiceInterface.php index cc8c0ef..cc8fd86 100644 --- a/app/Service/CouponRebateServiceInterface.php +++ b/app/Service/CouponRebateServiceInterface.php @@ -13,4 +13,6 @@ interface CouponRebateServiceInterface public function getActiveInfo(); + public function tieCouponActive($couponActivity,$couponForward,$couponRepay); + } \ No newline at end of file diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php new file mode 100644 index 0000000..d980954 --- /dev/null +++ b/app/Service/CouponService.php @@ -0,0 +1,141 @@ + 1, + 'not_receive' => [], + 'jump_data' => [ + 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, + 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, + 'coupons' => [] + ] + ]; + $nowTime = time(); + $c_ids = []; +$result['active_type'] = 1; + // 渠道开启,查询该渠道可以领取的优惠券ID + // 渠道未开启,查询所有优惠券 + if (env('SUB_CHANNEL') == 1) { + $c_ids = CouponUserRecType::where('receive_type', $receiveType)->pluck('system_coupon_user_id'); + } else { + $c_ids = Coupon::pluck('id'); + } + + $couponReceive = CouponRec::where('user_id',$userId); + + // 渠道开启,查询该用户在此渠道领过的优惠券ID + if (env('SUB_CHANNEL') == 1) { + $couponReceive->where('receive_type', $receiveType); + } + $cr_ids = $couponReceive->pluck('system_coupon_user_id'); + + // 可领取的券ID + $c_ids = $c_ids->toArray(); + // 已经领取的券ID + $cr_ids = $cr_ids->toArray(); + + // 当前用户可领的优惠券ID + $couponIds = array_diff($c_ids, $cr_ids); + + // 获取领取型优惠券 + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $couponRebateIds = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_FORWARD.$activityType); + // $result['active_type'] = $couponRebateIds; + // return $result; + $couponIds = ($couponRebateIds === false || empty($couponRebateIds)) ? $couponIds : array_merge($couponIds,$couponRebateIds) ; + + $whereC = [ + ['u.end_time','>',$nowTime], + ['u.start_time','<=',$nowTime], + ['u.status','=',1] + ]; + + if (env('SUB_CHANNEL') == 1) { + array_push($whereC, ['type.receive_type','=', $receiveType]); + } + + $coupons = Db::table('ims_system_coupon_user as u') + ->join('ims_system_coupon_user_receivetype as type', 'u.id', '=', 'type.system_coupon_user_id') + ->whereIn('u.id', $couponIds) + ->where($whereC) + ->whereRaw('u.inventory_use < u.inventory and u.inventory-u.inventory_use >= type.one_receive_number') + ->select('u.*','type.one_receive_number') + ->orderBy('u.weigh','desc') + ->limit(4) + ->get(); + + foreach ($coupons as $k => &$v){ + if($v['active_type'] == 1){ + $result['not_receive'] = $v; + }else if($v['active_type'] == 2){ + $result['jump_data']['coupons'][] = $v; + } + if($v->discount_type == 2){ + $v->discounts = floatval($v->discounts); + } + } + + $result['active_type'] = count($result['jump_data']['coupons']) > 0 ? 2 : $result['active_type'] ; + + return $result; + } + + //统计用户 + public function userCouponAccount() + { + + } + + /** + * 用户领取优惠卷 + */ + public function userReceiveCoupon() + { + + } + + /** + * 获取用户已经领取的优惠卷列表 + */ + public function getUserReceiveCouponList() + { + + } + + /** + * 获取用户当前订单可用的优惠券列表 + * 按分类(1订单 等优惠)分组返回 + */ + public function getUserAvailableCoupons() + { + + } + +} \ No newline at end of file diff --git a/app/Service/CouponServiceInterface.php b/app/Service/CouponServiceInterface.php new file mode 100644 index 0000000..b096ecd --- /dev/null +++ b/app/Service/CouponServiceInterface.php @@ -0,0 +1,18 @@ + Date: Thu, 6 Aug 2020 15:26:19 +0800 Subject: [PATCH 057/172] =?UTF-8?q?=E5=90=88=E5=B9=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 84 ++++++++++++++++------------- 1 file changed, 46 insertions(+), 38 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index dec3b75..da4b6da 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -37,13 +37,13 @@ class CouponRebateService implements CouponRebateServiceInterface $phone = $params["phone"]; $now = time(); $ids = is_array($ids) ? $ids : explode(',',$ids); - + // status: 0领取成功 >0领取失败 $result = [ 'status' => 1, 'coupon_text' => '继续努力~' ]; - + // 错误日志记录 $errorData = [ 'coupon_ids' =>$ids, @@ -54,24 +54,24 @@ class CouponRebateService implements CouponRebateServiceInterface ]; $receiveSsdb = []; - + try{ Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData,&$receiveSsdb) { $success = []; $fail = []; $isr = []; - + //读写锁,完全控制,性能低 $coupons = Coupon::whereIn('id', $ids)->lockForUpdate() - ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts','active_type') - ->get(); + ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts','active_type') + ->get(); foreach($coupons as $coupon){ $errorData['coupon_id'] = $coupon->id; //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内可领取, 否则返回领取失败的优惠券 - if ( + if ( $coupon->status == 1 && $coupon->inventory > $coupon->inventory_use @@ -81,7 +81,7 @@ class CouponRebateService implements CouponRebateServiceInterface $coupon->end_time >= $now && $coupon->active_type == 2 - ) + ) { // 查询一次能领取的数量 @@ -90,15 +90,15 @@ class CouponRebateService implements CouponRebateServiceInterface $couponReceiveType->where('receive_type',$receiveType); } $couponReceiveType = $couponReceiveType->first(); - + // 优惠券可领取数量 >= 本次领取数量 if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){ // 判断是否领取过 存在记录则领取过 $isReceive = CouponRec::select('id') - ->where('system_coupon_user_id',$coupon->id) - ->where('user_id',$userId) - ->exists(); + ->where('system_coupon_user_id',$coupon->id) + ->where('user_id',$userId) + ->exists(); if(!$isReceive){ //记录已领取的数量 @@ -116,7 +116,7 @@ class CouponRebateService implements CouponRebateServiceInterface $couponReceive->receive_type = $receiveType; $couponReceive->send_user_id = $sendUserId; $couponReceive->phone = $phone; - + // if ( $couponReceive->save() && $coupon->save() ) { // $success[] = $coupon; // $receiveSsdb[] = $coupon->id;; @@ -126,12 +126,12 @@ class CouponRebateService implements CouponRebateServiceInterface $receiveSsdb[] = $coupon->id; $result['status'] = 2; $result['coupon_text'] = '您已领取!赶快去下单吧~'; - + $errorData['msg'] = '用户已经领取了优惠券'; $this->log->event( LogLabel::COUPON_LOG, $errorData - ); + ); } }else{ $fail[] = $coupon; @@ -161,6 +161,13 @@ class CouponRebateService implements CouponRebateServiceInterface $result['coupon_text'] = '恭喜您领取成功!'; } }); + } catch (Exception $e){ + $errorData['msg'] = $e->getMessage(); + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + } if(count($receiveSsdb) > 0){ $saveSsdb = []; foreach($receiveSsdb as $kssdb => $vssdb){ @@ -186,11 +193,11 @@ class CouponRebateService implements CouponRebateServiceInterface public function isCouponRebate($user_id) { $res = Db::table('ims_system_coupon_user as u') - ->leftjoin('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id') + ->leftjoin('ims_system_coupon_user_receive as r', 'u.id', '=', 'r.system_coupon_user_id') ->where([ - ['r.user_id' ,'=', $user_id], - ['r.receive_type','=', 4], - ['u.active_type' ,'=', 2], + ['r.user_id', '=', $user_id], + ['r.receive_type', '=', 4], + ['u.active_type', '=', 2], ]) ->select('r.id') ->first(); @@ -205,13 +212,13 @@ class CouponRebateService implements CouponRebateServiceInterface $time = time(); $res = Db::table('ims_system_coupon_user') ->where([ - ['status' ,'=', 1], - ['active_type' ,'=', 2], - ['start_time' ,'<=', $time], - ['end_time' ,'>', $time], + ['status', '=', 1], + ['active_type', '=', 2], + ['start_time', '<=', $time], + ['end_time', '>', $time], ]) ->whereRaw('inventory > inventory_use') - ->orderBy('addtime','desc') + ->orderBy('addtime', 'desc') ->get(); return $res; } @@ -220,47 +227,47 @@ class CouponRebateService implements CouponRebateServiceInterface * 将优惠券绑定活动 * 领取优惠券 COUPON_REBATE_FORWARD 可多张 * 返还优惠券 COUPON_REBATE_REPAY 只一张 - */ - public function tieCouponActive($couponActivity,$couponForward,$couponRepay) + */ + public function tieCouponActive($couponActivity, $couponForward, $couponRepay) { $result = [ 'forward' => true, - 'repay' => true, + 'repay' => true, ]; $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - $rrss1 = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_FORWARD.$couponActivity); - $rrss2 = $ssdb->exec('get',SsdbKeysPrefix::COUPON_REBATE_REPAY.$couponActivity); - return [$rrss1,$rrss2]; + $rrss1 = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity); + $rrss2 = $ssdb->exec('get', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity); + return [$rrss1, $rrss2]; // 记录领取类型优惠券 $forwardData = []; - foreach($couponForward as $kForward => $vForward){ + foreach ($couponForward as $kForward => $vForward) { $forwardData[] = $kForward; $forwardData[] = $vForward; } - if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_FORWARD.$couponActivity,$forwardData)){ + if (false === $ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity, $forwardData)) { $this->log->event( LogLabel::COUPON_LOG, [ 'coupon_activity' => $couponActivity, - 'coupon_forward' => $forwardData, - 'msg' => '绑定-领取-优惠券到ssdb失败' + 'coupon_forward' => $forwardData, + 'msg' => '绑定-领取-优惠券到ssdb失败' ] ); $result['forward'] = false; }; // 记录返还类型优惠券 - if(false === $ssdb->exec('set',SsdbKeysPrefix::COUPON_REBATE_REPAY.$couponActivity,$couponRepay)){ + if (false === $ssdb->exec('set', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity, $couponRepay)) { $this->log->event( LogLabel::COUPON_LOG, [ 'coupon_activity' => $couponActivity, - 'coupon_Repay' => $couponRepay, - 'msg' => '绑定-返还-优惠券到ssdb失败' + 'coupon_Repay' => $couponRepay, + 'msg' => '绑定-返还-优惠券到ssdb失败' ] ); $result['repay'] = false; @@ -344,4 +351,5 @@ class CouponRebateService implements CouponRebateServiceInterface return '返券成功'; - }} \ No newline at end of file + } +} \ No newline at end of file From a529ccc46a9737c057dc6b6b61cee6e852f0393f Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Thu, 6 Aug 2020 15:27:47 +0800 Subject: [PATCH 058/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E5=8E=BB=E6=8E=89=E8=B0=83?= =?UTF-8?q?=E8=AF=95=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/SsdbKeysPrefix.php | 2 +- app/Service/CouponService.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Constants/SsdbKeysPrefix.php b/app/Constants/SsdbKeysPrefix.php index 2550f84..d747600 100644 --- a/app/Constants/SsdbKeysPrefix.php +++ b/app/Constants/SsdbKeysPrefix.php @@ -30,5 +30,5 @@ class SsdbKeysPrefix extends AbstractConstants /** * @Message("Coupon rebate Key Prefix") */ - const COUPON_REBATE_REPAY = 'coupon_rebate_REPAY_'; + const COUPON_REBATE_REPAY = 'coupon_rebate_repay_'; } diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index d980954..39c91c8 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -39,7 +39,7 @@ class CouponService implements CouponServiceInterface ]; $nowTime = time(); $c_ids = []; -$result['active_type'] = 1; + // 渠道开启,查询该渠道可以领取的优惠券ID // 渠道未开启,查询所有优惠券 if (env('SUB_CHANNEL') == 1) { From 3d764144c2161174cc0b95ac30b2553a2f9619a3 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Thu, 6 Aug 2020 15:49:18 +0800 Subject: [PATCH 059/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E4=BC=98=E6=83=A0=E5=88=B8=E6=8E=A5=E5=8F=A3getSystem?= =?UTF-8?q?CouponUserList?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 6 +++--- app/Service/CouponService.php | 13 +++++++------ 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index da4b6da..8bce00e 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -236,9 +236,9 @@ class CouponRebateService implements CouponRebateServiceInterface ]; $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - $rrss1 = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity); - $rrss2 = $ssdb->exec('get', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity); - return [$rrss1, $rrss2]; + // $rrss1 = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity); + // $rrss2 = $ssdb->exec('get', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity); + // return [$rrss2]; // 记录领取类型优惠券 $forwardData = []; foreach ($couponForward as $kForward => $vForward) { diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 39c91c8..67f9e56 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -33,7 +33,7 @@ class CouponService implements CouponServiceInterface 'not_receive' => [], 'jump_data' => [ 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, - 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, + 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, 'coupons' => [] ] ]; @@ -67,8 +67,7 @@ class CouponService implements CouponServiceInterface // 获取领取型优惠券 $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); $couponRebateIds = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_FORWARD.$activityType); - // $result['active_type'] = $couponRebateIds; - // return $result; + $couponIds = ($couponRebateIds === false || empty($couponRebateIds)) ? $couponIds : array_merge($couponIds,$couponRebateIds) ; $whereC = [ @@ -92,11 +91,13 @@ class CouponService implements CouponServiceInterface ->get(); foreach ($coupons as $k => &$v){ - if($v['active_type'] == 1){ + + if($v->active_type == 1){ $result['not_receive'] = $v; - }else if($v['active_type'] == 2){ - $result['jump_data']['coupons'][] = $v; + }else if($v->active_type == 2){ + $result['jump_data']['coupons'][] = $v->id; } + if($v->discount_type == 2){ $v->discounts = floatval($v->discounts); } From 7fdba93322e0c4e9cc54042889d70a8112cd32e3 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Thu, 6 Aug 2020 16:50:07 +0800 Subject: [PATCH 060/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E8=AE=B0=E5=BD=95=E6=B4=BB?= =?UTF-8?q?=E5=8A=A8=E6=B4=BB=E5=8A=A8=E6=A0=87=E8=AF=86=E5=80=BCactivity?= =?UTF-8?q?=5Ftype=E5=88=B0ssdb?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/SsdbKeysPrefix.php | 5 +++++ app/Service/CouponRebateService.php | 19 ++++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/app/Constants/SsdbKeysPrefix.php b/app/Constants/SsdbKeysPrefix.php index d747600..1e721c2 100644 --- a/app/Constants/SsdbKeysPrefix.php +++ b/app/Constants/SsdbKeysPrefix.php @@ -31,4 +31,9 @@ class SsdbKeysPrefix extends AbstractConstants * @Message("Coupon rebate Key Prefix") */ const COUPON_REBATE_REPAY = 'coupon_rebate_repay_'; + + /** + * @Message("Coupon rebate Key Prefix") + */ + const COUPON_REBATE_ACTIVITY = 'coupon_rebate_activity'; } diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 8bce00e..f46e973 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -233,12 +233,28 @@ class CouponRebateService implements CouponRebateServiceInterface $result = [ 'forward' => true, 'repay' => true, + 'activity' => true, ]; $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); // $rrss1 = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity); // $rrss2 = $ssdb->exec('get', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity); - // return [$rrss2]; + // $rrss3 = $ssdb->exec('get', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); + // return [$rrss3]; + + // 记录活动本次 activity_type 活动标志值 + if (false === $ssdb->exec('set', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $couponActivity)) { + + $this->log->event( + LogLabel::COUPON_LOG, + [ + 'coupon_activity' => $couponActivity, + 'msg' => '记录活动标志值(activity_type)到ssdb失败' + ] + ); + $result['activity'] = false; + }; + // 记录领取类型优惠券 $forwardData = []; foreach ($couponForward as $kForward => $vForward) { @@ -272,6 +288,7 @@ class CouponRebateService implements CouponRebateServiceInterface ); $result['repay'] = false; }; + return $result; } From d583c82bcd78487fb4403b6e4341b477441cae44 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 6 Aug 2020 17:25:10 +0800 Subject: [PATCH 061/172] =?UTF-8?q?app=5Fenv=E8=AE=BE=E7=BD=AE=E4=B8=BAloc?= =?UTF-8?q?al=E6=97=B6=E4=B8=8D=E8=BF=9B=E8=A1=8Capi=20auth?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit 371ecf76c89ec444796d8831b8594100272196ab) --- app/Middleware/Auth/ApiMiddleware.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Middleware/Auth/ApiMiddleware.php b/app/Middleware/Auth/ApiMiddleware.php index ce06bff..44cf3fc 100644 --- a/app/Middleware/Auth/ApiMiddleware.php +++ b/app/Middleware/Auth/ApiMiddleware.php @@ -39,7 +39,7 @@ class ApiMiddleware implements MiddlewareInterface public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { - if (env('APP_ENV') == 'dev') { + if (env('APP_ENV') == 'dev' || env('APP_ENV') == 'local') { return $handler->handle($request); } From 343a4be0b9be137c1a46af2dcccf79e86c83a11f Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Thu, 6 Aug 2020 17:51:17 +0800 Subject: [PATCH 062/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BC=98=E5=8C=96=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E9=A2=86=E5=8F=96=E4=BC=98=E6=83=A0=E5=88=B8=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 240 +++++++++++++++------------- 1 file changed, 128 insertions(+), 112 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index f46e973..a3bff6e 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -36,7 +36,7 @@ class CouponRebateService implements CouponRebateServiceInterface $sendUserId = $params["send_user_id"]; $phone = $params["phone"]; $now = time(); - $ids = is_array($ids) ? $ids : explode(',',$ids); + $idsData = is_array($ids) ? $ids : explode(',',$ids); // status: 0领取成功 >0领取失败 $result = [ @@ -53,81 +53,102 @@ class CouponRebateService implements CouponRebateServiceInterface 'phone' =>$phone ]; + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); $receiveSsdb = []; - try{ - Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData,&$receiveSsdb) { - - $success = []; - $fail = []; - $isr = []; - - //读写锁,完全控制,性能低 - $coupons = Coupon::whereIn('id', $ids)->lockForUpdate() - ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts','active_type') - ->get(); - - foreach($coupons as $coupon){ - $errorData['coupon_id'] = $coupon->id; - - //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内可领取, 否则返回领取失败的优惠券 - if ( - $coupon->status == 1 - && - $coupon->inventory > $coupon->inventory_use - && - $coupon->start_time <= $now - && - $coupon->end_time >= $now - && - $coupon->active_type == 2 - ) - { - - // 查询一次能领取的数量 - $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number'); - if (env('SUB_CHANNEL') == 1) { - $couponReceiveType->where('receive_type',$receiveType); - } - $couponReceiveType = $couponReceiveType->first(); - - // 优惠券可领取数量 >= 本次领取数量 - if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){ - - // 判断是否领取过 存在记录则领取过 - $isReceive = CouponRec::select('id') - ->where('system_coupon_user_id',$coupon->id) - ->where('user_id',$userId) - ->exists(); - - if(!$isReceive){ - //记录已领取的数量 - $coupon->inventory_use += $couponReceiveType->number; - - $couponReceive = new CouponRec; - $couponReceive->user_id = $userId; - $couponReceive->system_coupon_user_id = $coupon->id; - $couponReceive->order_main_id = 0; - $couponReceive->receive_time = $now; - $couponReceive->number = $couponReceiveType->one_receive_number; - $couponReceive->number_remain = $couponReceiveType->one_receive_number; - $couponReceive->status = 0; - $couponReceive->update_time = $now; - $couponReceive->receive_type = $receiveType; - $couponReceive->send_user_id = $sendUserId; - $couponReceive->phone = $phone; - - // if ( $couponReceive->save() && $coupon->save() ) { - // $success[] = $coupon; - // $receiveSsdb[] = $coupon->id;; - // } + // 判断是否已全部领取 + $couponActivity = $ssdb->exec('get', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); + $userReceiveCouponIds = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity); + if($userReceiveCouponIds !== false){ + $ids = array_diff($idsData, $userReceiveCouponIds); + }else{ + $ids = $idsData; + } + + if(count($ids) > 0){ + try{ + Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData,&$receiveSsdb) { + + $success = []; + $fail = []; + $isr = []; + + //读写锁,完全控制,性能低 + $coupons = Coupon::whereIn('id', $ids)->lockForUpdate() + ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts','active_type') + ->get(); + + foreach($coupons as $coupon){ + $errorData['coupon_id'] = $coupon->id; + + //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内可领取, 否则返回领取失败的优惠券 + if ( + $coupon->status == 1 + && + $coupon->inventory > $coupon->inventory_use + && + $coupon->start_time <= $now + && + $coupon->end_time >= $now + && + $coupon->active_type == 2 + ) + { + + // 查询一次能领取的数量 + $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number'); + if (env('SUB_CHANNEL') == 1) { + $couponReceiveType->where('receive_type',$receiveType); + } + $couponReceiveType = $couponReceiveType->first(); + + // 优惠券可领取数量 >= 本次领取数量 + if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){ + + // 判断是否领取过 存在记录则领取过 + $isReceive = CouponRec::select('id') + ->where('system_coupon_user_id',$coupon->id) + ->where('user_id',$userId) + ->exists(); + + if(!$isReceive){ + //记录已领取的数量 + $coupon->inventory_use += $couponReceiveType->number; + + $couponReceive = new CouponRec; + $couponReceive->user_id = $userId; + $couponReceive->system_coupon_user_id = $coupon->id; + $couponReceive->order_main_id = 0; + $couponReceive->receive_time = $now; + $couponReceive->number = $couponReceiveType->one_receive_number; + $couponReceive->number_remain = $couponReceiveType->one_receive_number; + $couponReceive->status = 0; + $couponReceive->update_time = $now; + $couponReceive->receive_type = $receiveType; + $couponReceive->send_user_id = $sendUserId; + $couponReceive->phone = $phone; + + // if ( $couponReceive->save() && $coupon->save() ) { + // $success[] = $coupon; + // $receiveSsdb[] = $coupon->id;; + // } + }else{ + $fail[] = $coupon; + $receiveSsdb[] = $coupon->id; + $result['status'] = 2; + $result['coupon_text'] = '您已领取!赶快去下单吧~'; + + $errorData['msg'] = '用户已经领取了优惠券'; + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + } }else{ $fail[] = $coupon; - $receiveSsdb[] = $coupon->id; - $result['status'] = 2; - $result['coupon_text'] = '您已领取!赶快去下单吧~'; - - $errorData['msg'] = '用户已经领取了优惠券'; + $errorData['remain_receive_number'] = $coupon->inventory - $coupon->inventory_use; + $errorData['one_receive_number'] = $couponReceiveType->one_receive_number; + $errorData['msg'] = '优惠券剩余数量不足'; $this->log->event( LogLabel::COUPON_LOG, $errorData @@ -135,55 +156,50 @@ class CouponRebateService implements CouponRebateServiceInterface } }else{ $fail[] = $coupon; - $errorData['remain_receive_number'] = $coupon->inventory - $coupon->inventory_use; - $errorData['one_receive_number'] = $couponReceiveType->one_receive_number; - $errorData['msg'] = '优惠券剩余数量不足'; + $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完'; $this->log->event( LogLabel::COUPON_LOG, $errorData ); } - }else{ - $fail[] = $coupon; - $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完'; - $this->log->event( - LogLabel::COUPON_LOG, - $errorData - ); } - } - $result['data'] = [ - 'success' => $success, - 'fail' => $fail - ]; - if(count($success) > 0){ - $result['status'] = 0; - $result['coupon_text'] = '恭喜您领取成功!'; - } - }); - } catch (Exception $e){ - $errorData['msg'] = $e->getMessage(); - $this->log->event( - LogLabel::COUPON_LOG, - $errorData - ); - } - if(count($receiveSsdb) > 0){ - $saveSsdb = []; - foreach($receiveSsdb as $kssdb => $vssdb){ - $saveSsdb[] = $kssdb; - $saveSsdb[] = $vssdb; - } - // 记录到ssdb - $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE.$userId,$saveSsdb)){ - $errorData['msg'] = '记录领取优惠券到ssdb失败'; + $result['data'] = [ + 'success' => $success, + 'fail' => $fail + ]; + if(count($success) > 0){ + $result['status'] = 0; + $result['coupon_text'] = '恭喜您领取成功!'; + } + }); + } catch (Exception $e){ + $errorData['msg'] = $e->getMessage(); $this->log->event( LogLabel::COUPON_LOG, $errorData ); - }; + } + + if(count($receiveSsdb) > 0){ + $saveSsdb = []; + foreach($receiveSsdb as $kssdb => $vssdb){ + $saveSsdb[] = $kssdb; + $saveSsdb[] = $vssdb; + } + // 记录到ssdb + if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE.$userId,$saveSsdb)){ + $errorData['msg'] = '记录领取优惠券到ssdb失败'; + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + }; + } + }else{ + $result['status'] = 2; + $result['coupon_text'] = '您已领取!赶快去下单吧~'; } + return $result; } @@ -242,8 +258,8 @@ class CouponRebateService implements CouponRebateServiceInterface // $rrss3 = $ssdb->exec('get', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); // return [$rrss3]; - // 记录活动本次 activity_type 活动标志值 - if (false === $ssdb->exec('set', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $couponActivity)) { + // 记录活动本次 activity_type 活动标志值 + if (false === $ssdb->exec('set', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $couponActivity)) { $this->log->event( LogLabel::COUPON_LOG, From 1a177615b96428daee09e84c1ef7b2fb58581fae Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Fri, 7 Aug 2020 10:08:11 +0800 Subject: [PATCH 063/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E6=B4=BB=E5=8A=A8=E6=A0=87=E5=BF=97acrtivity=5Ftype?= =?UTF-8?q?=E4=B8=BA=E9=80=9A=E8=BF=87ssdb=E8=8E=B7=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 18 +++++++++--------- app/Service/CouponService.php | 12 +++++++----- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index a3bff6e..c31cf19 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -36,7 +36,7 @@ class CouponRebateService implements CouponRebateServiceInterface $sendUserId = $params["send_user_id"]; $phone = $params["phone"]; $now = time(); - $idsData = is_array($ids) ? $ids : explode(',',$ids); + $idsData = is_array($ids) ? $ids : explode(',',$ids); // status: 0领取成功 >0领取失败 $result = [ @@ -57,8 +57,8 @@ class CouponRebateService implements CouponRebateServiceInterface $receiveSsdb = []; // 判断是否已全部领取 - $couponActivity = $ssdb->exec('get', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); - $userReceiveCouponIds = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity); + $couponActivity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY,0); + $userReceiveCouponIds = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $couponActivity . $userId); if($userReceiveCouponIds !== false){ $ids = array_diff($idsData, $userReceiveCouponIds); }else{ @@ -187,7 +187,7 @@ class CouponRebateService implements CouponRebateServiceInterface $saveSsdb[] = $vssdb; } // 记录到ssdb - if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE.$userId,$saveSsdb)){ + if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $couponActivity . $userId, $saveSsdb)){ $errorData['msg'] = '记录领取优惠券到ssdb失败'; $this->log->event( LogLabel::COUPON_LOG, @@ -254,12 +254,12 @@ class CouponRebateService implements CouponRebateServiceInterface $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); // $rrss1 = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity); - // $rrss2 = $ssdb->exec('get', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity); - // $rrss3 = $ssdb->exec('get', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); - // return [$rrss3]; + // $rrss2 = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity,0); + // $rrss3 = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY,0); + // return [$rrss1,$rrss2,$rrss3]; // 记录活动本次 activity_type 活动标志值 - if (false === $ssdb->exec('set', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $couponActivity)) { + if (false === $ssdb->exec('hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, [0,$couponActivity])) { $this->log->event( LogLabel::COUPON_LOG, @@ -292,7 +292,7 @@ class CouponRebateService implements CouponRebateServiceInterface }; // 记录返还类型优惠券 - if (false === $ssdb->exec('set', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity, $couponRepay)) { + if (false === $ssdb->exec('hset', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity, [0,$couponRepay])) { $this->log->event( LogLabel::COUPON_LOG, diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 67f9e56..c0ff451 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -27,13 +27,16 @@ class CouponService implements CouponServiceInterface */ public function getSystemCouponUserList($userId,$receiveType) { - $activityType = 2;/* 优惠券活动标志 2 */ + /* 优惠券活动标志 2 */ + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $couponActivity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY,0); + $result = [ 'active_type' => 1, 'not_receive' => [], 'jump_data' => [ - 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, - 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, + 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$couponActivity, + 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$couponActivity, 'coupons' => [] ] ]; @@ -65,8 +68,7 @@ class CouponService implements CouponServiceInterface $couponIds = array_diff($c_ids, $cr_ids); // 获取领取型优惠券 - $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - $couponRebateIds = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_FORWARD.$activityType); + $couponRebateIds = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_FORWARD.$couponActivity); $couponIds = ($couponRebateIds === false || empty($couponRebateIds)) ? $couponIds : array_merge($couponIds,$couponRebateIds) ; From 5961de7d49adab31d000458076e7e3502eab7dfc Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Fri, 7 Aug 2020 10:25:26 +0800 Subject: [PATCH 064/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E7=BA=A2=E5=8C=85--=E9=A2=86=E5=8F=96=E4=BC=98?= =?UTF-8?q?=E6=83=A0=E5=88=B8=E6=8E=A5=E5=8F=A3=E4=BF=AE=E6=94=B9=EF=BC=8C?= =?UTF-8?q?=E4=B9=8B=E5=89=8D=E5=B0=86=E4=BF=9D=E5=AD=98=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E6=B3=A8=E9=87=8A=E8=B0=83=E8=AF=95=EF=BC=8C=E7=8E=B0=E5=9C=A8?= =?UTF-8?q?=E5=8E=BB=E6=8E=89=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index c31cf19..be0225a 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -64,14 +64,13 @@ class CouponRebateService implements CouponRebateServiceInterface }else{ $ids = $idsData; } - + if(count($ids) > 0){ try{ Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData,&$receiveSsdb) { $success = []; $fail = []; - $isr = []; //读写锁,完全控制,性能低 $coupons = Coupon::whereIn('id', $ids)->lockForUpdate() @@ -128,14 +127,14 @@ class CouponRebateService implements CouponRebateServiceInterface $couponReceive->send_user_id = $sendUserId; $couponReceive->phone = $phone; - // if ( $couponReceive->save() && $coupon->save() ) { - // $success[] = $coupon; - // $receiveSsdb[] = $coupon->id;; - // } + if ( $couponReceive->save() && $coupon->save() ) { + $success[] = $coupon; + $receiveSsdb[] = $coupon->id;; + } }else{ $fail[] = $coupon; $receiveSsdb[] = $coupon->id; - $result['status'] = 2; + $result['status'] = 3; $result['coupon_text'] = '您已领取!赶快去下单吧~'; $errorData['msg'] = '用户已经领取了优惠券'; From 8d1582cfd590fc03747420ad7a655b002870c425 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Fri, 7 Aug 2020 10:53:20 +0800 Subject: [PATCH 065/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8--=E4=BF=AE=E6=94=B9=E9=A2=86=E5=8F=96=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3-ssdb=E8=AE=B0=E5=BD=95=E5=85=A8=E9=A2=86=E5=8F=96?= =?UTF-8?q?=E7=9A=84=E4=BC=98=E6=83=A0=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index be0225a..660e433 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -61,6 +61,7 @@ class CouponRebateService implements CouponRebateServiceInterface $userReceiveCouponIds = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $couponActivity . $userId); if($userReceiveCouponIds !== false){ $ids = array_diff($idsData, $userReceiveCouponIds); + $receiveSsdb = $userReceiveCouponIds; }else{ $ids = $idsData; } @@ -129,7 +130,7 @@ class CouponRebateService implements CouponRebateServiceInterface if ( $couponReceive->save() && $coupon->save() ) { $success[] = $coupon; - $receiveSsdb[] = $coupon->id;; + $receiveSsdb[] = $coupon->id; } }else{ $fail[] = $coupon; From e3b323d2a71c432b7a3cf29613e7f7346274af1f Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 7 Aug 2020 12:06:12 +0800 Subject: [PATCH 066/172] =?UTF-8?q?SSDB=20Task=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit e5ead242086db660d887f340c169a222d7c1a94d) --- app/Libs/SimpleSSDB.php | 2 +- app/TaskWorker/SSDBTask.php | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/app/Libs/SimpleSSDB.php b/app/Libs/SimpleSSDB.php index b6920b2..c829bda 100644 --- a/app/Libs/SimpleSSDB.php +++ b/app/Libs/SimpleSSDB.php @@ -78,7 +78,7 @@ class SSDB function __construct($host, $port, $timeout_ms=2000){ $timeout_f = (float)$timeout_ms/1000; - $this->sock = @stream_socket_client("[$host]:$port", $errno, $errstr, $timeout_f); + $this->sock = @stream_socket_client("$host:$port", $errno, $errstr, $timeout_f); if(!$this->sock){ throw new SSDBException("$errno: $errstr"); } diff --git a/app/TaskWorker/SSDBTask.php b/app/TaskWorker/SSDBTask.php index 9c6ef29..fd4d451 100644 --- a/app/TaskWorker/SSDBTask.php +++ b/app/TaskWorker/SSDBTask.php @@ -24,6 +24,13 @@ class SSDBTask return $result; } + public function execWithoutTask($method,...$args) + { + $result = $this->client()->__call($method,$args); + + return $result; + } + protected function client(){ if ($this->ss instanceof SimpleSSDB) { return $this->ss; From 7d989e3d6f4349ce6c977202d9b6f7889ca8837d Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Fri, 7 Aug 2020 12:07:40 +0800 Subject: [PATCH 067/172] =?UTF-8?q?=E8=BF=94=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 115 ++++++++++++++++++---------- 1 file changed, 73 insertions(+), 42 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index be0225a..6641015 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -312,6 +312,18 @@ class CouponRebateService implements CouponRebateServiceInterface */ public function couponRebate($order_id) { + //$ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + // $active_id = $ssdb->exec('get',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); + // $rebate_id = $ssdb->exec('get',SsdbKeysPrefix::COUPON_REBATE_REPAY.$active_id); + $rebate_id = 56; + //判断该优惠券是否有库存 + $inventory = Db::table('ims_system_coupon_user') + ->where('id',$rebate_id) + ->whereRaw('inventory > inventory_use') + ->exists(); + if(!$inventory){ + return '库存不足'; + } /* 判断优惠券类型是否为转发活动优惠券 */ $coupon = Db::table('ims_system_coupon_user_receive as r') ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id') @@ -322,63 +334,82 @@ class CouponRebateService implements CouponRebateServiceInterface ['r.receive_type', '=', 4], ['u.status', '=', 1], ]) - ->select('r.id', 'r.send_user_id', 'u.system_coupon_id') + ->select('r.id', 'r.user_id', 'r.send_user_id', 'u.system_coupon_id') ->first(); /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/ if (isset($coupon->send_user_id) && ($coupon->send_user_id) > 0) { - //判断该优惠券是否有库存 -// $inventory = Db::table('system_coupon_user_receive as r'); -// if($inventory['inventory'] <= 0){ -// return '库存不足'; -// } - //return $exist_coupon; + //是否已返过券 + $exists_coupon_rebate = Db::table('ims_system_coupon_user_receive') + ->where([ + ['system_coupon_user_id' ,'=', $rebate_id], + ['user_id' ,'=', $coupon->send_user_id], + ['receive_type' ,'=', 5], + ['status' ,'=', 0], + ]) + ->exists(); //开启事务 + Db::beginTransaction(); try { /* * 如果已有该优惠券 则领取数量 和 可用数量 自增1 * 否则新增一条返券记录 */ - $nowTime = time(); - $res = Db::table('ims_system_coupon_user_receive')->moreIncrementOrInsert( - [ - 'system_coupon_user_id' => $coupon->system_coupon_id, - 'user_id' => $coupon->send_user_id, - 'receive_type' => 5, - 'status' => 0, - ], - [ - 'order_main_id' => $order_id, - 'receive_time' => $nowTime, - 'update_time' => $nowTime, - 'created_at' => $nowTime, - 'updated_at' => $nowTime, - ], - [ - 'number' => 1, - 'number_remain' => 1, - ] - ); -// if ($res) { -// //首次返券更新rebate_type字段 防止重复返券 -// Db::table('system_coupon_user_receive')->where('id', $coupon->id)->update(['rebate_type' => 2]); -// //更新库存操作 -// Db::table('system_coupon_user') -// ->where('id', $coupon->id) -// ->increment('inventory_use'); -// } else { -// Db::rollBack(); -// return '事务失败'; -// } + if($exists_coupon_rebate){ + var_dump(222); + Db::table('ims_system_coupon_user_receive') + ->where([ + ['user_id' ,'=', $coupon->send_user_id], + ['receive_type' ,'=', 5], + ]) + ->increment('number'); + Db::table('ims_system_coupon_user_receive') + ->where([ + ['user_id' ,'=', $coupon->send_user_id], + ['receive_type' ,'=', 5], + ]) + ->increment('number_remain'); + }else { + var_dump(111111222); + $nowTime = time(); + Db::table('ims_system_coupon_user_receive')->insert([ + [ + 'user_id' => $coupon->send_user_id, + 'system_coupon_user_id' => $rebate_id, + 'receive_type' => 5, + 'status' => 0, + 'number' => 1, + 'number_remain' => 1, + 'order_main_id' => $order_id, + 'receive_time' => $nowTime, + 'update_time' => $nowTime, + 'created_at' => $nowTime, + 'updated_at' => $nowTime, + ] + ]); + } + //首次返券更新rebate_type字段 防止重复返券 + Db::table('ims_system_coupon_user_receive') + ->where([ + ['user_id','=',$coupon->user_id], + ['receive_type','=',4], + ]) + ->update(['rebate_type' => 2]); + //更新库存操作 + Db::table('ims_system_coupon_user') + ->where('id', $rebate_id) + ->increment('inventory_use'); // 提交 Db::commit(); } catch (\Exception $e) { // 回滚 Db::rollBack(); - return '返券失败'; + $errorData['order_main_id'] = $order_id; + $errorData['msg'] = '返券失败'; + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); } - } else { -// $str1 = 'order_main_id:'.$this->order_id . ',未查询到用户领取优惠券信息['.$coupon.']'; -// $this->couponErrorLog($str1); } From b0e417ff34b3849d7305277d8bbd79bb0752af05 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 7 Aug 2020 16:33:56 +0800 Subject: [PATCH 068/172] =?UTF-8?q?=E6=98=AF=E5=90=A6=E5=B9=B3=E5=8F=B0?= =?UTF-8?q?=E6=96=B0=E7=94=A8=E6=88=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Model/OrderMain.php | 10 +++++++++ app/Service/UserService.php | 31 ++++++++++++++++++++++++++++ app/Service/UserServiceInterface.php | 15 ++++++++++++++ config/autoload/dependencies.php | 1 + config/autoload/middlewares.php | 2 +- 5 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 app/Model/OrderMain.php create mode 100644 app/Service/UserService.php create mode 100644 app/Service/UserServiceInterface.php diff --git a/app/Model/OrderMain.php b/app/Model/OrderMain.php new file mode 100644 index 0000000..7c7eb3d --- /dev/null +++ b/app/Model/OrderMain.php @@ -0,0 +1,10 @@ +where(['user_id' => $user_id]) + ->where(function ($query){ + $query->where('state', 'in', [4,5,10]) + ->orWhere('dm_state', 'in', [2,3]); + }) + ->exists(); + + return !$exist; + } +} \ No newline at end of file diff --git a/app/Service/UserServiceInterface.php b/app/Service/UserServiceInterface.php new file mode 100644 index 0000000..c5bf647 --- /dev/null +++ b/app/Service/UserServiceInterface.php @@ -0,0 +1,15 @@ + \App\Service\AdService::class, \App\Commons\Log::class => \App\Commons\Log::class, \App\Service\CouponRebateServiceInterface::class => \App\Service\CouponRebateService::class, + \App\Service\UserServiceInterface::class => \App\Service\UserService::class, ]; diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index 5eb19a5..2befbcd 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -11,8 +11,8 @@ declare(strict_types=1); */ return [ 'http' => [ + \App\Middleware\CorsMiddleware::class, \App\Middleware\Auth\ApiMiddleware::class, \Hyperf\Validation\Middleware\ValidationMiddleware::class, - \App\Middleware\CorsMiddleware::class, ], ]; From e695f5553d593d05b8de188dedc64bea23819945 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Fri, 7 Aug 2020 17:43:21 +0800 Subject: [PATCH 069/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8--=E6=B7=BB=E5=8A=A0=E6=B8=85=E9=99=A4=E9=A2=86?= =?UTF-8?q?=E5=8F=96=E8=AE=B0=E5=BD=95=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 12 +- app/Service/CouponRebateService.php | 234 +++++++------------ app/Service/CouponRebateServiceInterface.php | 4 +- app/Service/CouponService.php | 13 +- config/routes.php | 4 +- 5 files changed, 110 insertions(+), 157 deletions(-) diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 84ef098..dd9ed65 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -73,10 +73,20 @@ class CouponRebateController extends BaseController public function tieCouponActive(CouponRebateTieRequest $validator) { $couponForward = $this->request->input('coupon_forward_ids',[]); - $couponForward = is_array($couponForward) ? $couponForward : explode(',',$couponForward) ; + $couponForward = is_array($couponForward) ? implode(',',$couponForward) : $couponForward ; $couponRepay = $this->request->input('coupon_repay_id',0); $couponActivity = $this->request->input('coupon_activity',0); $res = $this->CouponRebateService->tieCouponActive($couponActivity,$couponForward,$couponRepay); return $this->success($res); } + + /** + * 清优惠券领取记录(SSDB) + */ + public function clearSsdbCouponReceiveByName(){ + $activity = $this->request->input('activity_type',0); + $userId = $this->request->input('user_id',0); + $get = $this->request->input('get',0); + return $this->success($this->CouponRebateService->clearSsdbCouponReceiveByName($activity,$userId, $get)); + } } diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 660e433..ecc0c6a 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -14,6 +14,8 @@ use App\TaskWorker\SSDBTask; use App\Constants\SsdbKeysPrefix; use Exception; +use function AlibabaCloud\Client\json; + class CouponRebateService implements CouponRebateServiceInterface { /** @@ -35,7 +37,6 @@ class CouponRebateService implements CouponRebateServiceInterface $ids = $params["ids"]; $sendUserId = $params["send_user_id"]; $phone = $params["phone"]; - $now = time(); $idsData = is_array($ids) ? $ids : explode(',',$ids); // status: 0领取成功 >0领取失败 @@ -54,119 +55,85 @@ class CouponRebateService implements CouponRebateServiceInterface ]; $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $activity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY ,'activity'); $receiveSsdb = []; - // 判断是否已全部领取 - $couponActivity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY,0); - $userReceiveCouponIds = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $couponActivity . $userId); - if($userReceiveCouponIds !== false){ + // 判断是否已全部领取过 + $userReceive = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId); + if($userReceive === false){ + $ids = $idsData; + }else{ + $userReceiveCouponIds = empty($userReceive) ? [] : $userReceive ; $ids = array_diff($idsData, $userReceiveCouponIds); $receiveSsdb = $userReceiveCouponIds; - }else{ - $ids = $idsData; } if(count($ids) > 0){ try{ - Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData,&$receiveSsdb) { - + Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,&$result,&$errorData,&$receiveSsdb) { + + $now = time(); $success = []; - $fail = []; - //读写锁,完全控制,性能低 + //获取优惠券信息 (读写锁,完全控制,性能低) $coupons = Coupon::whereIn('id', $ids)->lockForUpdate() - ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts','active_type') + ->where('active_type',2) + ->where('status',1) + ->where('start_time', '<=', $now) + ->where('end_time', '>=', $now) + ->whereRaw('inventory > inventory_use') + ->select('id','title','inventory','inventory_use','full_amount','discounts','active_type') ->get(); foreach($coupons as $coupon){ $errorData['coupon_id'] = $coupon->id; - - //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内可领取, 否则返回领取失败的优惠券 - if ( - $coupon->status == 1 - && - $coupon->inventory > $coupon->inventory_use - && - $coupon->start_time <= $now - && - $coupon->end_time >= $now - && - $coupon->active_type == 2 - ) - { - - // 查询一次能领取的数量 - $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number'); - if (env('SUB_CHANNEL') == 1) { - $couponReceiveType->where('receive_type',$receiveType); - } - $couponReceiveType = $couponReceiveType->first(); - - // 优惠券可领取数量 >= 本次领取数量 - if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){ - - // 判断是否领取过 存在记录则领取过 - $isReceive = CouponRec::select('id') - ->where('system_coupon_user_id',$coupon->id) - ->where('user_id',$userId) - ->exists(); - - if(!$isReceive){ - //记录已领取的数量 - $coupon->inventory_use += $couponReceiveType->number; - - $couponReceive = new CouponRec; - $couponReceive->user_id = $userId; - $couponReceive->system_coupon_user_id = $coupon->id; - $couponReceive->order_main_id = 0; - $couponReceive->receive_time = $now; - $couponReceive->number = $couponReceiveType->one_receive_number; - $couponReceive->number_remain = $couponReceiveType->one_receive_number; - $couponReceive->status = 0; - $couponReceive->update_time = $now; - $couponReceive->receive_type = $receiveType; - $couponReceive->send_user_id = $sendUserId; - $couponReceive->phone = $phone; - - if ( $couponReceive->save() && $coupon->save() ) { - $success[] = $coupon; - $receiveSsdb[] = $coupon->id; - } + + // 查询一次能领取的数量 + $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number'); + if (env('SUB_CHANNEL') == 1) { + $couponReceiveType->where('receive_type',$receiveType); + } + $couponReceiveType = $couponReceiveType->first(); + + // 优惠券可领取数量 >= 本次领取数量 + if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){ + + // 判断是否领取过 存在记录则领取过 + $isReceive = CouponRec::select('id') + ->where('system_coupon_user_id',$coupon->id) + ->where('user_id',$userId) + ->exists(); + + if(!$isReceive){ + //记录已领取的数量 + $coupon->inventory_use += $couponReceiveType->number; + + $couponReceive = new CouponRec; + $couponReceive->user_id = $userId; + $couponReceive->system_coupon_user_id = $coupon->id; + $couponReceive->order_main_id = 0; + $couponReceive->receive_time = $now; + $couponReceive->number = $couponReceiveType->one_receive_number; + $couponReceive->number_remain = $couponReceiveType->one_receive_number; + $couponReceive->status = 0; + $couponReceive->update_time = $now; + $couponReceive->receive_type = $receiveType; + $couponReceive->send_user_id = $sendUserId; + $couponReceive->phone = $phone; + + if ( $couponReceive->save() && $coupon->save() ) { + $success[] = $coupon; + $receiveSsdb[] = $coupon->id; }else{ - $fail[] = $coupon; - $receiveSsdb[] = $coupon->id; - $result['status'] = 3; - $result['coupon_text'] = '您已领取!赶快去下单吧~'; - - $errorData['msg'] = '用户已经领取了优惠券'; + $errorData['msg'] = '添加优惠券到用户领取表或者记录已领取数量失败'; $this->log->event( LogLabel::COUPON_LOG, $errorData ); } - }else{ - $fail[] = $coupon; - $errorData['remain_receive_number'] = $coupon->inventory - $coupon->inventory_use; - $errorData['one_receive_number'] = $couponReceiveType->one_receive_number; - $errorData['msg'] = '优惠券剩余数量不足'; - $this->log->event( - LogLabel::COUPON_LOG, - $errorData - ); } - }else{ - $fail[] = $coupon; - $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完'; - $this->log->event( - LogLabel::COUPON_LOG, - $errorData - ); } } - $result['data'] = [ - 'success' => $success, - 'fail' => $fail - ]; if(count($success) > 0){ $result['status'] = 0; $result['coupon_text'] = '恭喜您领取成功!'; @@ -187,8 +154,8 @@ class CouponRebateService implements CouponRebateServiceInterface $saveSsdb[] = $vssdb; } // 记录到ssdb - if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $couponActivity . $userId, $saveSsdb)){ - $errorData['msg'] = '记录领取优惠券到ssdb失败'; + if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId, $saveSsdb)){ + $errorData['msg'] = '记录领取优惠券到ssdb失败'; $this->log->event( LogLabel::COUPON_LOG, $errorData @@ -246,64 +213,19 @@ class CouponRebateService implements CouponRebateServiceInterface */ public function tieCouponActive($couponActivity, $couponForward, $couponRepay) { - $result = [ - 'forward' => true, - 'repay' => true, - 'activity' => true, - ]; - + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - // $rrss1 = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity); - // $rrss2 = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity,0); - // $rrss3 = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY,0); - // return [$rrss1,$rrss2,$rrss3]; - - // 记录活动本次 activity_type 活动标志值 - if (false === $ssdb->exec('hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, [0,$couponActivity])) { - - $this->log->event( - LogLabel::COUPON_LOG, - [ - 'coupon_activity' => $couponActivity, - 'msg' => '记录活动标志值(activity_type)到ssdb失败' - ] - ); - $result['activity'] = false; - }; - // 记录领取类型优惠券 - $forwardData = []; - foreach ($couponForward as $kForward => $vForward) { - $forwardData[] = $kForward; - $forwardData[] = $vForward; - } - - if (false === $ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity, $forwardData)) { - - $this->log->event( - LogLabel::COUPON_LOG, - [ - 'coupon_activity' => $couponActivity, - 'coupon_forward' => $forwardData, - 'msg' => '绑定-领取-优惠券到ssdb失败' - ] - ); - $result['forward'] = false; - }; - - // 记录返还类型优惠券 - if (false === $ssdb->exec('hset', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity, [0,$couponRepay])) { + $data = [ + 'activity', $couponActivity, + 'forward' , $couponForward, + 'repay' , $couponRepay + ]; - $this->log->event( - LogLabel::COUPON_LOG, - [ - 'coupon_activity' => $couponActivity, - 'coupon_Repay' => $couponRepay, - 'msg' => '绑定-返还-优惠券到ssdb失败' - ] - ); - $result['repay'] = false; - }; + $result = [ + 'result' => ($ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $data) === false) ? false : true , + 'data' => $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY) + ]; return $result; } @@ -385,4 +307,22 @@ class CouponRebateService implements CouponRebateServiceInterface return '返券成功'; } + + /** + * 清优惠券领取记录(SSDB) + */ + public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0){ + + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + + if($get > 0){ + return [ + $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ), + $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $userId ), + SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId + ]; + } + + return ( $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ) === false) ? false : true; + } } \ No newline at end of file diff --git a/app/Service/CouponRebateServiceInterface.php b/app/Service/CouponRebateServiceInterface.php index 0e97dca..6b6edf9 100644 --- a/app/Service/CouponRebateServiceInterface.php +++ b/app/Service/CouponRebateServiceInterface.php @@ -15,6 +15,8 @@ interface CouponRebateServiceInterface public function tieCouponActive($couponActivity,$couponForward,$couponRepay); - public function couponRebate($order_id); + public function couponRebate($order_id); + + public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0); } \ No newline at end of file diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index c0ff451..915dc6e 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -29,14 +29,15 @@ class CouponService implements CouponServiceInterface { /* 优惠券活动标志 2 */ $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - $couponActivity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY,0); + $couponActivity = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); + $activityType = $couponActivity === false ? 0 : $couponActivity['activity']; $result = [ 'active_type' => 1, 'not_receive' => [], 'jump_data' => [ - 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$couponActivity, - 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$couponActivity, + 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, + 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, 'coupons' => [] ] ]; @@ -67,10 +68,8 @@ class CouponService implements CouponServiceInterface // 当前用户可领的优惠券ID $couponIds = array_diff($c_ids, $cr_ids); - // 获取领取型优惠券 - $couponRebateIds = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_FORWARD.$couponActivity); - - $couponIds = ($couponRebateIds === false || empty($couponRebateIds)) ? $couponIds : array_merge($couponIds,$couponRebateIds) ; + // 获取领取型优惠券 + $couponIds = $couponActivity['forward'] === false ? $couponIds : array_merge($couponIds,explode(',',$couponActivity['forward'])); $whereC = [ ['u.end_time','>',$nowTime], diff --git a/config/routes.php b/config/routes.php index f2a579b..174546f 100644 --- a/config/routes.php +++ b/config/routes.php @@ -31,5 +31,7 @@ Router::addGroup('/v1/',function (){ Router::post('CouponRebate/getActiveInfo', 'App\Controller\CouponRebateController@getActiveInfo'); Router::post('CouponRebate/tieCouponActive', 'App\Controller\CouponRebateController@tieCouponActive'); - Router::post('CouponRebate/couponRebate', 'App\Controller\CouponRebateController@couponRebate'); + Router::post('CouponRebate/couponRebate', 'App\Controller\CouponRebateController@couponRebate'); + Router::post('CouponRebate/clearSsdbReceive', 'App\Controller\CouponRebateController@clearSsdbCouponReceiveByName'); + }); \ No newline at end of file From 0dbf1b1b17da7f1f4380d6938115d10045ca7566 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Fri, 7 Aug 2020 18:19:56 +0800 Subject: [PATCH 070/172] =?UTF-8?q?=E8=BF=94=E5=88=B8=20=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 12 ++- app/Service/CouponRebateService.php | 89 ++++++++++++++-------- 2 files changed, 67 insertions(+), 34 deletions(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index 475c7b9..e04615e 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -4,16 +4,19 @@ declare(strict_types=1); namespace App\Amqp\Consumer; +use App\Constants\SsdbKeysPrefix; use Hyperf\Amqp\Result; use Hyperf\Amqp\Annotation\Consumer; use Hyperf\Amqp\Message\ConsumerMessage; +use Hyperf\Utils\ApplicationContext; use PhpAmqpLib\Message\AMQPMessage; use App\Service\CouponRebateService; use App\Service\CouponRebateServiceInterface; use Hyperf\Di\Annotation\Inject; + /** - * @Consumer(exchange="couponRebate", routingKey="couponRebate", queue="couponRebate", name ="couponRebateConsumer", nums=1) + * @Consumer(exchange="couponRebate1", routingKey="couponRebate1", queue="couponRebate1", name ="couponRebateConsumer", nums=1) */ class couponRebateConsumer extends ConsumerMessage { @@ -25,10 +28,11 @@ class couponRebateConsumer extends ConsumerMessage public function consumeMessage($data, AMQPMessage $message): string { - var_dump($data); - var_dump($message->getBody()); + //var_dump($data); + //ar_dump($rebate_id); + //var_dump($message->getBody()); $res = $this->CouponRebateService->couponRebate($data); - var_dump($res); + //var_dump($res); if (false) { return Result::REQUEUE; } diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index d3474ff..b3db743 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -208,8 +208,13 @@ class CouponRebateService implements CouponRebateServiceInterface * */ public function isCouponRebate($user_id) { + //获取SSDB上的活动信息 + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); + $coupon_ids = explode(',',$active['forward']); $res = Db::table('ims_system_coupon_user as u') ->leftjoin('ims_system_coupon_user_receive as r', 'u.id', '=', 'r.system_coupon_user_id') + ->whereIn('r.system_coupon_user_id',$coupon_ids) ->where([ ['r.user_id', '=', $user_id], ['r.receive_type', '=', 4], @@ -225,8 +230,13 @@ class CouponRebateService implements CouponRebateServiceInterface */ public function getActiveInfo() { + //获取SSDB上的活动信息 + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); + $coupon_ids = explode(',',$active['forward']); $time = time(); $res = Db::table('ims_system_coupon_user') + ->whereIn('id',$coupon_ids) ->where([ ['status', '=', 1], ['active_type', '=', 2], @@ -234,6 +244,7 @@ class CouponRebateService implements CouponRebateServiceInterface ['end_time', '>', $time], ]) ->whereRaw('inventory > inventory_use') + ->orderBy('weigh', 'desc') ->orderBy('addtime', 'desc') ->get(); return $res; @@ -313,19 +324,22 @@ class CouponRebateService implements CouponRebateServiceInterface */ public function couponRebate($order_id) { - //$ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - // $active_id = $ssdb->exec('get',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); - // $rebate_id = $ssdb->exec('get',SsdbKeysPrefix::COUPON_REBATE_REPAY.$active_id); - $rebate_id = 56; - //判断该优惠券是否有库存 + //获取SSDB上的活动信息 + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $active = $ssdb->execWithoutTask('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); + //判断返券优惠券是否有库存 $inventory = Db::table('ims_system_coupon_user') - ->where('id',$rebate_id) + ->where('id',$active['repay']) ->whereRaw('inventory > inventory_use') ->exists(); if(!$inventory){ return '库存不足'; } - /* 判断优惠券类型是否为转发活动优惠券 */ + + //获取活动发放优惠券id + $coupon_ids = explode(',',$active['forward']); + + /* 判断被使用的优惠券类型是否为转发活动优惠券 */ $coupon = Db::table('ims_system_coupon_user_receive as r') ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id') ->where([ @@ -333,49 +347,52 @@ class CouponRebateService implements CouponRebateServiceInterface ['r.send_user_id', '>', 0], ['r.rebate_type', '=', 1], ['r.receive_type', '=', 4], - ['u.status', '=', 1], ]) - ->select('r.id', 'r.user_id', 'r.send_user_id', 'u.system_coupon_id') + ->whereIn('r.system_coupon_user_id',$coupon_ids) + ->select('r.user_id', 'r.send_user_id') ->first(); /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/ if (isset($coupon->send_user_id) && ($coupon->send_user_id) > 0) { //是否已返过券 $exists_coupon_rebate = Db::table('ims_system_coupon_user_receive') ->where([ - ['system_coupon_user_id' ,'=', $rebate_id], + ['system_coupon_user_id' ,'=', $active['repay']], ['user_id' ,'=', $coupon->send_user_id], ['receive_type' ,'=', 5], - ['status' ,'=', 0], ]) - ->exists(); + ->select('id','status') + ->first(); //开启事务 Db::beginTransaction(); try { - /* - * 如果已有该优惠券 则领取数量 和 可用数量 自增1 - * 否则新增一条返券记录 - */ - if($exists_coupon_rebate){ - var_dump(222); + //返券 + if($exists_coupon_rebate->id){ + //如果已有该优惠券 则领取数量 和 可用数量 自增1 Db::table('ims_system_coupon_user_receive') ->where([ - ['user_id' ,'=', $coupon->send_user_id], - ['receive_type' ,'=', 5], + ['id' ,'=', $exists_coupon_rebate->id], ]) ->increment('number'); Db::table('ims_system_coupon_user_receive') ->where([ - ['user_id' ,'=', $coupon->send_user_id], - ['receive_type' ,'=', 5], + ['id' ,'=', $exists_coupon_rebate->id], ]) ->increment('number_remain'); + //如果该用户在领取表中 status为已用完状态 2 则改为已用部分 1 + if($exists_coupon_rebate->status == 2){ + Db::table('ims_system_coupon_user_receive') + ->where([ + ['id' ,'=', $exists_coupon_rebate->id], + ]) + ->update(['status' => 1]);; + } }else { - var_dump(111111222); + //否则新增一条返券记录 $nowTime = time(); Db::table('ims_system_coupon_user_receive')->insert([ [ 'user_id' => $coupon->send_user_id, - 'system_coupon_user_id' => $rebate_id, + 'system_coupon_user_id' => $active['repay'], 'receive_type' => 5, 'status' => 0, 'number' => 1, @@ -394,26 +411,38 @@ class CouponRebateService implements CouponRebateServiceInterface ['user_id','=',$coupon->user_id], ['receive_type','=',4], ]) + ->whereIn('system_coupon_user_id',$coupon_ids) ->update(['rebate_type' => 2]); //更新库存操作 Db::table('ims_system_coupon_user') - ->where('id', $rebate_id) + ->where('id', $active['repay']['repay']) ->increment('inventory_use'); + // 提交 Db::commit(); } catch (\Exception $e) { // 回滚 Db::rollBack(); - $errorData['order_main_id'] = $order_id; - $errorData['msg'] = '返券失败'; + $log_Data = array(); + $log_Data['name'] = '返券'; + $log_Data['order_main_id'] = $order_id; + $log_Data['msg'] = '返券失败'; $this->log->event( LogLabel::COUPON_LOG, - $errorData + $log_Data ); } } - - + $log_Data = array(); + $log_Data['name'] = '返券'; + $log_Data['user_id'] = $order_id; + $log_Data['send_user_id'] = $coupon->send_user_id; + $log_Data['order_main_id'] = $order_id; + $log_Data['msg'] = '返券成功'; + $this->log->event( + LogLabel::COUPON_LOG, + $log_Data + ); return '返券成功'; } } \ No newline at end of file From 6eb8019119d686760a4a32c8242c752183eeaec6 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Fri, 7 Aug 2020 18:24:54 +0800 Subject: [PATCH 071/172] =?UTF-8?q?=E8=BF=94=E5=88=B8=20=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 2 +- app/Service/CouponRebateService.php | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index e04615e..239aee7 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -33,7 +33,7 @@ class couponRebateConsumer extends ConsumerMessage //var_dump($message->getBody()); $res = $this->CouponRebateService->couponRebate($data); //var_dump($res); - if (false) { + if (!$res) { return Result::REQUEUE; } return Result::ACK; diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index cc65a8e..233a4ae 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -255,7 +255,8 @@ class CouponRebateService implements CouponRebateServiceInterface ->whereRaw('inventory > inventory_use') ->exists(); if(!$inventory){ - return '库存不足'; + //库存不足 + return false; } //获取活动发放优惠券id @@ -365,7 +366,7 @@ class CouponRebateService implements CouponRebateServiceInterface LogLabel::COUPON_LOG, $log_Data ); - return '返券成功'; + return true; } /** From 73fc7fa73d938f633027f477143afb345ce2da6e Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Fri, 7 Aug 2020 19:16:14 +0800 Subject: [PATCH 072/172] =?UTF-8?q?=E8=BF=94=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index 239aee7..bca6310 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -16,7 +16,7 @@ use Hyperf\Di\Annotation\Inject; /** - * @Consumer(exchange="couponRebate1", routingKey="couponRebate1", queue="couponRebate1", name ="couponRebateConsumer", nums=1) + * @Consumer(exchange="couponRebate", routingKey="couponRebate", queue="couponRebate", name ="couponRebateConsumer", nums=1) */ class couponRebateConsumer extends ConsumerMessage { From 907bc495511de1f86a5a1e833d7b6ebf3fb5a15b Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Fri, 7 Aug 2020 19:22:18 +0800 Subject: [PATCH 073/172] =?UTF-8?q?=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index bca6310..7ac8e0d 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -28,11 +28,7 @@ class couponRebateConsumer extends ConsumerMessage public function consumeMessage($data, AMQPMessage $message): string { - //var_dump($data); - //ar_dump($rebate_id); - //var_dump($message->getBody()); $res = $this->CouponRebateService->couponRebate($data); - //var_dump($res); if (!$res) { return Result::REQUEUE; } From e043558427c6c2b26ecbd251f2b7ec0fadb01343 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Mon, 10 Aug 2020 16:30:00 +0800 Subject: [PATCH 074/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E5=87=8F=E5=BA=93=E5=AD=98?= =?UTF-8?q?=EF=BC=88=E5=8A=A0=E9=A2=86=E5=8F=96=E9=87=8F=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 233a4ae..138b7a9 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -106,7 +106,7 @@ class CouponRebateService implements CouponRebateServiceInterface if(!$isReceive){ //记录已领取的数量 - $coupon->inventory_use += $couponReceiveType->number; + $coupon->inventory_use += $couponReceiveType->one_receive_number; $couponReceive = new CouponRec; $couponReceive->user_id = $userId; @@ -378,9 +378,7 @@ class CouponRebateService implements CouponRebateServiceInterface if($get > 0){ return [ - $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ), - $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $userId ), - SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId + $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ) ]; } From 1272da173d2a1dcb33a2e08ffc7b68dee92ed0f6 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Mon, 10 Aug 2020 19:35:05 +0800 Subject: [PATCH 075/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BC=98=E6=83=A0=E5=88=B8?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=EF=BC=88getSystemCouponUserList=EF=BC=89?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=BF=94=E5=9B=9E=E8=83=8C=E6=99=AF=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponService.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 915dc6e..f43af83 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -36,9 +36,11 @@ class CouponService implements CouponServiceInterface 'active_type' => 1, 'not_receive' => [], 'jump_data' => [ - 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, + 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, - 'coupons' => [] + 'share_bg' => "https://img.lanzulive.com/attachment/images/background/dangmian_dialog_background.png", + 'receive_bg' => "https://img.lanzulive.com/attachment/images/background/dangmian_dialog_background.png", + 'coupons' => [] ] ]; $nowTime = time(); From 7a8803643b81e4e0569b793a3327b1eb47613819 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Mon, 10 Aug 2020 20:38:57 +0800 Subject: [PATCH 076/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E4=BC=98=E6=83=A0=E5=88=B8=E5=88=86=E4=BA=AB=E8=83=8C?= =?UTF-8?q?=E6=99=AF=E5=9B=BE=E7=89=87=E6=97=B6=E7=9A=84=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E5=9F=9F=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponService.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index f43af83..8b50689 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -38,8 +38,8 @@ class CouponService implements CouponServiceInterface 'jump_data' => [ 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, - 'share_bg' => "https://img.lanzulive.com/attachment/images/background/dangmian_dialog_background.png", - 'receive_bg' => "https://img.lanzulive.com/attachment/images/background/dangmian_dialog_background.png", + 'share_bg' => env('OSS_IMG_HOST')."/attachment/images/background/dangmian_dialog_background.png", + 'receive_bg' => env('OSS_IMG_HOST')."/attachment/images/background/dangmian_dialog_background.png", 'coupons' => [] ] ]; From 8e01b4e319c735794df2ee743fb9538192cf9e9f Mon Sep 17 00:00:00 2001 From: Mike Date: Mon, 10 Aug 2020 21:01:20 +0800 Subject: [PATCH 077/172] =?UTF-8?q?=E4=BF=AE=E6=94=B9log=20host=E5=9C=B0?= =?UTF-8?q?=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Commons/Log.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Commons/Log.php b/app/Commons/Log.php index bf5fb24..29a4e84 100644 --- a/app/Commons/Log.php +++ b/app/Commons/Log.php @@ -61,7 +61,7 @@ class Log ] ]; $client->post( - 'http://39.96.12.39:3100/loki/api/v1/push', + env('LOG_HOST','http://39.96.12.39:3100').'/loki/api/v1/push', [ 'headers'=>[ 'Content-Type'=>'application/json' From 5febaa87c28accd3252539352886139533f780e6 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Mon, 10 Aug 2020 21:15:08 +0800 Subject: [PATCH 078/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E5=88=86?= =?UTF-8?q?=E4=BA=AB=E8=83=8C=E6=99=AF=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 8b50689..7c365f0 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -38,7 +38,7 @@ class CouponService implements CouponServiceInterface 'jump_data' => [ 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, - 'share_bg' => env('OSS_IMG_HOST')."/attachment/images/background/dangmian_dialog_background.png", + 'share_bg' => env('OSS_IMG_HOST')."/attachment/images/png/2020/08/10/23245eea88db680670df67e77e0d8d7e.png", 'receive_bg' => env('OSS_IMG_HOST')."/attachment/images/background/dangmian_dialog_background.png", 'coupons' => [] ] From d4fb2d20c4bf580bcf300a9b081f92ddc74a1b70 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 11 Aug 2020 09:12:23 +0800 Subject: [PATCH 079/172] =?UTF-8?q?=E4=BF=AE=E6=94=B9amqp=E9=85=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index 7ac8e0d..f9a3808 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -16,7 +16,7 @@ use Hyperf\Di\Annotation\Inject; /** - * @Consumer(exchange="couponRebate", routingKey="couponRebate", queue="couponRebate", name ="couponRebateConsumer", nums=1) + * @Consumer(exchange="deviceCouponRebate", routingKey="deviceCouponRebate", queue="deviceCouponRebate", name ="couponRebateConsumer", nums=1) */ class couponRebateConsumer extends ConsumerMessage { @@ -28,6 +28,7 @@ class couponRebateConsumer extends ConsumerMessage public function consumeMessage($data, AMQPMessage $message): string { + var_dump($data); $res = $this->CouponRebateService->couponRebate($data); if (!$res) { return Result::REQUEUE; From 866fcf15f467af65fd6c0253c2ad1f2ee2382bf6 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 11 Aug 2020 10:18:43 +0800 Subject: [PATCH 080/172] =?UTF-8?q?=E8=BF=94=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 2 +- app/Service/CouponRebateService.php | 20 +++++--------------- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index f9a3808..c3eb85a 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -16,7 +16,7 @@ use Hyperf\Di\Annotation\Inject; /** - * @Consumer(exchange="deviceCouponRebate", routingKey="deviceCouponRebate", queue="deviceCouponRebate", name ="couponRebateConsumer", nums=1) + * @Consumer(exchange="deviceCouponRebate1", routingKey="deviceCouponRebate1", queue="deviceCouponRebate1", name ="couponRebateConsumer", nums=1) */ class couponRebateConsumer extends ConsumerMessage { diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 233a4ae..de89875 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -267,15 +267,15 @@ class CouponRebateService implements CouponRebateServiceInterface ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id') ->where([ ['u.order_main_id', '=', $order_id], - ['r.send_user_id', '>', 0], - ['r.rebate_type', '=', 1], - ['r.receive_type', '=', 4], + // ['r.send_user_id', '>', 0], + // ['r.rebate_type', '=', 1], + // ['r.receive_type', '=', 4], ]) ->whereIn('r.system_coupon_user_id',$coupon_ids) ->select('r.user_id', 'r.send_user_id') ->first(); /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/ - if (isset($coupon->send_user_id) && ($coupon->send_user_id) > 0) { + if ($coupon) { //是否已返过券 $exists_coupon_rebate = Db::table('ims_system_coupon_user_receive') ->where([ @@ -289,7 +289,7 @@ class CouponRebateService implements CouponRebateServiceInterface Db::beginTransaction(); try { //返券 - if($exists_coupon_rebate->id){ + if($exists_coupon_rebate){ //如果已有该优惠券 则领取数量 和 可用数量 自增1 Db::table('ims_system_coupon_user_receive') ->where([ @@ -356,16 +356,6 @@ class CouponRebateService implements CouponRebateServiceInterface ); } } - $log_Data = array(); - $log_Data['name'] = '返券'; - $log_Data['user_id'] = $order_id; - $log_Data['send_user_id'] = $coupon->send_user_id; - $log_Data['order_main_id'] = $order_id; - $log_Data['msg'] = '返券成功'; - $this->log->event( - LogLabel::COUPON_LOG, - $log_Data - ); return true; } From 8d2ca49c8369560e4fb954288a9c4f09c01ea2c7 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 11 Aug 2020 10:20:19 +0800 Subject: [PATCH 081/172] =?UTF-8?q?=E8=BF=94=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index c3eb85a..f9a3808 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -16,7 +16,7 @@ use Hyperf\Di\Annotation\Inject; /** - * @Consumer(exchange="deviceCouponRebate1", routingKey="deviceCouponRebate1", queue="deviceCouponRebate1", name ="couponRebateConsumer", nums=1) + * @Consumer(exchange="deviceCouponRebate", routingKey="deviceCouponRebate", queue="deviceCouponRebate", name ="couponRebateConsumer", nums=1) */ class couponRebateConsumer extends ConsumerMessage { From cd45fe61c3ce1b4d4087f56b0c186a666bf88a48 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 11 Aug 2020 10:21:46 +0800 Subject: [PATCH 082/172] =?UTF-8?q?=E8=BF=94=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index de89875..3864091 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -267,9 +267,9 @@ class CouponRebateService implements CouponRebateServiceInterface ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id') ->where([ ['u.order_main_id', '=', $order_id], - // ['r.send_user_id', '>', 0], - // ['r.rebate_type', '=', 1], - // ['r.receive_type', '=', 4], + ['r.send_user_id', '>', 0], + ['r.rebate_type', '=', 1], + ['r.receive_type', '=', 4], ]) ->whereIn('r.system_coupon_user_id',$coupon_ids) ->select('r.user_id', 'r.send_user_id') From 72178dea359298bdab7355c826ebe4397ee37b5b Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 11 Aug 2020 11:22:33 +0800 Subject: [PATCH 083/172] =?UTF-8?q?=E8=BF=94=E5=88=B8=E5=BA=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 3864091..a3384ff 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -338,7 +338,7 @@ class CouponRebateService implements CouponRebateServiceInterface ->update(['rebate_type' => 2]); //更新库存操作 Db::table('ims_system_coupon_user') - ->where('id', $active['repay']['repay']) + ->where('id', $active['repay']) ->increment('inventory_use'); // 提交 From b1156b71a3ff43979bdcf5ff8a4b39f10b691e30 Mon Sep 17 00:00:00 2001 From: weigang Date: Tue, 11 Aug 2020 12:57:08 +0800 Subject: [PATCH 084/172] =?UTF-8?q?Token=20name=E8=87=AA=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/ParamsTokenSsdbService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/ParamsTokenSsdbService.php b/app/Service/ParamsTokenSsdbService.php index 65bd113..8aa60e2 100644 --- a/app/Service/ParamsTokenSsdbService.php +++ b/app/Service/ParamsTokenSsdbService.php @@ -26,7 +26,7 @@ class ParamsTokenSsdbService implements ParamsTokenServiceInterface */ public function generate($params) { - $token = md5(json_encode($params)); + $token = $params['token_name'] ?? md5(json_encode($params)); $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); From 7e51571ec36f24140d7b4056b3e4bdbb98d0064d Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 11 Aug 2020 15:31:54 +0800 Subject: [PATCH 085/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E9=A2=86?= =?UTF-8?q?=E5=8F=96=E4=BC=98=E6=83=A0=E5=88=B8=E5=AD=98ssdb=E7=9A=84?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 3 +- app/Service/CouponRebateService.php | 43 ++++++++++++-------- app/Service/CouponRebateServiceInterface.php | 2 +- app/Service/CouponService.php | 2 +- 4 files changed, 30 insertions(+), 20 deletions(-) diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index dd9ed65..3f4064b 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -87,6 +87,7 @@ class CouponRebateController extends BaseController $activity = $this->request->input('activity_type',0); $userId = $this->request->input('user_id',0); $get = $this->request->input('get',0); - return $this->success($this->CouponRebateService->clearSsdbCouponReceiveByName($activity,$userId, $get)); + $isAll = $this->request->input('is_all',0);; + return $this->success($this->CouponRebateService->clearSsdbCouponReceiveByName($activity,$userId, $get, $isAll)); } } diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 138b7a9..8d27c16 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -56,14 +56,16 @@ class CouponRebateService implements CouponRebateServiceInterface $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); $activity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY ,'activity'); + // ssdb 键值 + $ssdbKey = 'activity_'.$activity.'_user_'.$userId; $receiveSsdb = []; // 判断是否已全部领取过 - $userReceive = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId); + $userReceive = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE,$ssdbKey); if($userReceive === false){ $ids = $idsData; }else{ - $userReceiveCouponIds = empty($userReceive) ? [] : $userReceive ; + $userReceiveCouponIds = empty($userReceive) ? [] : explode(',',$userReceive) ; $ids = array_diff($idsData, $userReceiveCouponIds); $receiveSsdb = $userReceiveCouponIds; } @@ -148,13 +150,12 @@ class CouponRebateService implements CouponRebateServiceInterface } if(count($receiveSsdb) > 0){ - $saveSsdb = []; - foreach($receiveSsdb as $kssdb => $vssdb){ - $saveSsdb[] = $kssdb; - $saveSsdb[] = $vssdb; - } - // 记录到ssdb - if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId, $saveSsdb)){ +; + $saveSsdb = [ + $ssdbKey, + implode(',',$receiveSsdb) + ]; + if(false === $ssdb->exec('hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $saveSsdb)){ $errorData['msg'] = '记录领取优惠券到ssdb失败'; $this->log->event( LogLabel::COUPON_LOG, @@ -372,16 +373,24 @@ class CouponRebateService implements CouponRebateServiceInterface /** * 清优惠券领取记录(SSDB) */ - public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0){ - + public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0, $isAll = 0){ + $key = 'activity_'.$activity.'_user_'.$userId; $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - if($get > 0){ - return [ - $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ) - ]; + if($isAll > 0){ + if($get > 0){ + return $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE); + }else{ + return ( $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE) === false) ? false : true ; + } + }else { + $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ); + + if($get > 0){ + return $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key); + }else{ + return ( $ssdb->exec('hdel', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key) === false) ? false : true ; + } } - - return ( $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ) === false) ? false : true; } } \ No newline at end of file diff --git a/app/Service/CouponRebateServiceInterface.php b/app/Service/CouponRebateServiceInterface.php index 6b6edf9..df8fc5d 100644 --- a/app/Service/CouponRebateServiceInterface.php +++ b/app/Service/CouponRebateServiceInterface.php @@ -17,6 +17,6 @@ interface CouponRebateServiceInterface public function couponRebate($order_id); - public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0); + public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0, $isAll = 0); } \ No newline at end of file diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 7c365f0..8ee46a2 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -38,7 +38,7 @@ class CouponService implements CouponServiceInterface 'jump_data' => [ 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, - 'share_bg' => env('OSS_IMG_HOST')."/attachment/images/png/2020/08/10/23245eea88db680670df67e77e0d8d7e.png", + 'share_bg' => env('OSS_IMG_HOST').'/attachment/images/png/2020/08/11/23245eea88db680670df67e77e0d8d7e.png', 'receive_bg' => env('OSS_IMG_HOST')."/attachment/images/background/dangmian_dialog_background.png", 'coupons' => [] ] From 4e26801b4d9ef7302022eb3642f94851c3affaef Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 11 Aug 2020 15:34:26 +0800 Subject: [PATCH 086/172] =?UTF-8?q?=E8=BF=94=E5=88=B8=E5=90=88=E5=B9=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 2 +- app/Constants/SsdbKeysPrefix.php | 10 ++++++++++ app/Service/CouponRebateService.php | 17 ++++++++++++++--- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index f9a3808..c3eb85a 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -16,7 +16,7 @@ use Hyperf\Di\Annotation\Inject; /** - * @Consumer(exchange="deviceCouponRebate", routingKey="deviceCouponRebate", queue="deviceCouponRebate", name ="couponRebateConsumer", nums=1) + * @Consumer(exchange="deviceCouponRebate1", routingKey="deviceCouponRebate1", queue="deviceCouponRebate1", name ="couponRebateConsumer", nums=1) */ class couponRebateConsumer extends ConsumerMessage { diff --git a/app/Constants/SsdbKeysPrefix.php b/app/Constants/SsdbKeysPrefix.php index 1e721c2..0eaad4b 100644 --- a/app/Constants/SsdbKeysPrefix.php +++ b/app/Constants/SsdbKeysPrefix.php @@ -36,4 +36,14 @@ class SsdbKeysPrefix extends AbstractConstants * @Message("Coupon rebate Key Prefix") */ const COUPON_REBATE_ACTIVITY = 'coupon_rebate_activity'; + + /** + * @Message("Store New User") + */ + const STORE_NEW_USER = 'store_new_user_'; + + /** + * @Message("Coupon rebate List") + */ + const COUPON_REBATE_LIST = 'coupon_rebate_list'; } diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index a3384ff..245ab7c 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -274,8 +274,11 @@ class CouponRebateService implements CouponRebateServiceInterface ->whereIn('r.system_coupon_user_id',$coupon_ids) ->select('r.user_id', 'r.send_user_id') ->first(); - /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/ - if ($coupon) { + /* 如果使用的优惠券为转发活动优惠券 + **则给赠送者返一张优惠券 + * **自己给自己转发的券不给返券 + */ + if ($coupon && ($coupon->user_id != $coupon->send_user_id)) { //是否已返过券 $exists_coupon_rebate = Db::table('ims_system_coupon_user_receive') ->where([ @@ -341,6 +344,14 @@ class CouponRebateService implements CouponRebateServiceInterface ->where('id', $active['repay']) ->increment('inventory_use'); + //添加领取记录到ssdb + $data = [ + 'msg', '领券', + 'order_id',$order_id, + 'user_id' , $coupon->user_id, + 'send_usr_id' , $coupon->send_user_id + ]; + $ssdb->execWithoutTask('multi_hset', SsdbKeysPrefix::COUPON_REBATE_LIST, $data); // 提交 Db::commit(); } catch (\Exception $e) { @@ -348,7 +359,7 @@ class CouponRebateService implements CouponRebateServiceInterface Db::rollBack(); $log_Data = array(); $log_Data['name'] = '返券'; - $log_Data['order_main_id'] = $order_id; + $log_Data['order_id'] = $order_id; $log_Data['msg'] = '返券失败'; $this->log->event( LogLabel::COUPON_LOG, From 6d4c4d32402365886a17cd117b3ce788560ca8e4 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 11 Aug 2020 15:54:23 +0800 Subject: [PATCH 087/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E5=88=86=E4=BA=AB?= =?UTF-8?q?=E8=83=8C=E6=99=AF=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 8ee46a2..afcb702 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -38,7 +38,7 @@ class CouponService implements CouponServiceInterface 'jump_data' => [ 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, - 'share_bg' => env('OSS_IMG_HOST').'/attachment/images/png/2020/08/11/23245eea88db680670df67e77e0d8d7e.png', + 'share_bg' => env('OSS_IMG_HOST').'/attachment/images/png/2020/08/11/d697d43b91913f861f931649f0898815.png', 'receive_bg' => env('OSS_IMG_HOST')."/attachment/images/background/dangmian_dialog_background.png", 'coupons' => [] ] From 33ad505c93bc4fdb2b14a895c172963868dd787f Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 11 Aug 2020 17:31:57 +0800 Subject: [PATCH 088/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E8=83=8C?= =?UTF-8?q?=E6=99=AF=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index afcb702..2d76319 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -39,7 +39,7 @@ class CouponService implements CouponServiceInterface 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, 'share_bg' => env('OSS_IMG_HOST').'/attachment/images/png/2020/08/11/d697d43b91913f861f931649f0898815.png', - 'receive_bg' => env('OSS_IMG_HOST')."/attachment/images/background/dangmian_dialog_background.png", + 'receive_bg' => env('OSS_IMG_HOST')."/attachment/images/png/2020/08/11/9c7d7c95b5de29539fad4bc9a2fcb98d.png", 'coupons' => [] ] ]; From dbb96dad6b884b82b22e8069bc925bf15f270ade Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Tue, 11 Aug 2020 18:18:55 +0800 Subject: [PATCH 089/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 2d76319..b0aa716 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -96,7 +96,7 @@ class CouponService implements CouponServiceInterface foreach ($coupons as $k => &$v){ if($v->active_type == 1){ - $result['not_receive'] = $v; + $result['not_receive'][] = $v; }else if($v->active_type == 2){ $result['jump_data']['coupons'][] = $v->id; } From bb193b9d46c4344127303b86b350454ace7313ae Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 11 Aug 2020 19:34:18 +0800 Subject: [PATCH 090/172] =?UTF-8?q?=E5=B7=B2=E9=A2=86=E5=8F=96=E4=BC=98?= =?UTF-8?q?=E6=83=A0=E5=88=B8=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 1 - app/Constants/SsdbKeysPrefix.php | 2 +- app/Controller/CouponController.php | 11 +++++- app/Service/CouponRebateService.php | 39 ++++++++++------------ 4 files changed, 29 insertions(+), 24 deletions(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index c3eb85a..9a0a414 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -28,7 +28,6 @@ class couponRebateConsumer extends ConsumerMessage public function consumeMessage($data, AMQPMessage $message): string { - var_dump($data); $res = $this->CouponRebateService->couponRebate($data); if (!$res) { return Result::REQUEUE; diff --git a/app/Constants/SsdbKeysPrefix.php b/app/Constants/SsdbKeysPrefix.php index 0eaad4b..bf76f9d 100644 --- a/app/Constants/SsdbKeysPrefix.php +++ b/app/Constants/SsdbKeysPrefix.php @@ -45,5 +45,5 @@ class SsdbKeysPrefix extends AbstractConstants /** * @Message("Coupon rebate List") */ - const COUPON_REBATE_LIST = 'coupon_rebate_list'; + const COUPON_REBATE_LIST = 'coupon_rebate_list_'; } diff --git a/app/Controller/CouponController.php b/app/Controller/CouponController.php index 6212782..7b86286 100644 --- a/app/Controller/CouponController.php +++ b/app/Controller/CouponController.php @@ -153,11 +153,20 @@ class CouponController extends BaseController ['receive.user_id','=',$userId], ]) ->whereIn('receive.status',[0,1]) - ->select('u.*','receive.number_remain') + ->select('u.discounts','u.full_amount','u.introduce','u.usable_end_time','receive.number_remain') ->orderBy('u.weigh','desc') ->get(); foreach ($coupons as $key => $coupon) { + //拼接满减文字提示 + $coupon->full_amount = '满' . $coupon->full_amount . "可用"; + //判断是折扣优惠券还是满减优惠券 + if($coupon->discount_type == 1){ + $coupon->discounts = '¥ '.$coupon->discounts; + }elseif($coupon->discount_type == 2){ + $coupon->discounts = floatval($coupon->discounts)."折"; + } + if ($coupon->usable_end_time < $nowTime || $coupon->number_remain <= 0) { $expired[] = $coupon; } else { diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 0af991f..f139207 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -176,21 +176,19 @@ class CouponRebateService implements CouponRebateServiceInterface * */ public function isCouponRebate($user_id) { - //获取SSDB上的活动信息 $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); - $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); - $coupon_ids = explode(',',$active['forward']); - $res = Db::table('ims_system_coupon_user as u') - ->leftjoin('ims_system_coupon_user_receive as r', 'u.id', '=', 'r.system_coupon_user_id') - ->whereIn('r.system_coupon_user_id',$coupon_ids) - ->where([ - ['r.user_id', '=', $user_id], - ['r.receive_type', '=', 4], - ['u.active_type', '=', 2], - ]) - ->select('r.id') - ->first(); - return $res; + $activity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY ,'activity'); + // ssdb 键值 + $ssdbKey = 'activity_'.$activity.'_user_'.$user_id; + + // 判断是否已全部领取过 + $userReceive = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE,$ssdbKey); + if($userReceive === false || is_null($userReceive)){ + return false; + }else{ + return $userReceive; + } + } /* @@ -201,6 +199,7 @@ class CouponRebateService implements CouponRebateServiceInterface //获取SSDB上的活动信息 $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); + return $active; $coupon_ids = explode(',',$active['forward']); $time = time(); $res = Db::table('ims_system_coupon_user') @@ -347,17 +346,13 @@ class CouponRebateService implements CouponRebateServiceInterface //添加领取记录到ssdb $data = [ - 'msg', '领券', - 'order_id',$order_id, - 'user_id' , $coupon->user_id, - 'send_usr_id' , $coupon->send_user_id + $order_id,$coupon->user_id, ]; - $ssdb->execWithoutTask('multi_hset', SsdbKeysPrefix::COUPON_REBATE_LIST, $data); + $ssdb->execWithoutTask('multi_hset', SsdbKeysPrefix::COUPON_REBATE_LIST.$coupon->send_user_id, $data); // 提交 Db::commit(); } catch (\Exception $e) { - // 回滚 - Db::rollBack(); + //写入日志文件 $log_Data = array(); $log_Data['name'] = '返券'; $log_Data['order_id'] = $order_id; @@ -366,6 +361,8 @@ class CouponRebateService implements CouponRebateServiceInterface LogLabel::COUPON_LOG, $log_Data ); + // 回滚 + Db::rollBack(); } } return true; From da9df22b7dc92f9d4034ed95c0054b9a8fe6d72a Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 11 Aug 2020 19:42:40 +0800 Subject: [PATCH 091/172] =?UTF-8?q?=E5=B7=B2=E9=A2=86=E5=8F=96=E7=BA=A2?= =?UTF-8?q?=E5=8C=85=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Controller/CouponController.php b/app/Controller/CouponController.php index 7b86286..04adf9c 100644 --- a/app/Controller/CouponController.php +++ b/app/Controller/CouponController.php @@ -153,7 +153,7 @@ class CouponController extends BaseController ['receive.user_id','=',$userId], ]) ->whereIn('receive.status',[0,1]) - ->select('u.discounts','u.full_amount','u.introduce','u.usable_end_time','receive.number_remain') + ->select('u.title','u.discounts','u.full_amount','u.discount_type','u.introduce','u.usable_end_time','receive.number_remain') ->orderBy('u.weigh','desc') ->get(); From 68215280bd137d81ffaca6a34d25b50bb8fcdc83 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 11 Aug 2020 19:56:33 +0800 Subject: [PATCH 092/172] =?UTF-8?q?=E5=B7=B2=E9=A2=86=E5=8F=96=E4=BC=98?= =?UTF-8?q?=E6=83=A0=E5=88=B8=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponController.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/app/Controller/CouponController.php b/app/Controller/CouponController.php index 04adf9c..5585fba 100644 --- a/app/Controller/CouponController.php +++ b/app/Controller/CouponController.php @@ -162,10 +162,13 @@ class CouponController extends BaseController $coupon->full_amount = '满' . $coupon->full_amount . "可用"; //判断是折扣优惠券还是满减优惠券 if($coupon->discount_type == 1){ - $coupon->discounts = '¥ '.$coupon->discounts; + $coupon->discounts = '¥'.$coupon->discounts; }elseif($coupon->discount_type == 2){ $coupon->discounts = floatval($coupon->discounts)."折"; } + //失效时间格式转换 + $usable_end_time = date('Y-m-d H:i:s',$coupon->usable_end_time); + $coupon->usable_end_time = '有效期至:'.$usable_end_time; if ($coupon->usable_end_time < $nowTime || $coupon->number_remain <= 0) { $expired[] = $coupon; From 207ac3ced0bf07d5cbe7e378743155742e524da9 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 11 Aug 2020 20:03:18 +0800 Subject: [PATCH 093/172] =?UTF-8?q?=E8=BF=94=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 1 - 1 file changed, 1 deletion(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index f139207..d5b12f2 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -199,7 +199,6 @@ class CouponRebateService implements CouponRebateServiceInterface //获取SSDB上的活动信息 $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); - return $active; $coupon_ids = explode(',',$active['forward']); $time = time(); $res = Db::table('ims_system_coupon_user') From 55beb100aea5a25268da5e98e0f0160595f9e091 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Tue, 11 Aug 2020 21:06:17 +0800 Subject: [PATCH 094/172] =?UTF-8?q?=E8=8E=B7=E5=8F=96=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E5=B7=B2=E9=A2=86=E5=8F=96=E4=BC=98=E6=83=A0=E5=88=B8=E5=88=97?= =?UTF-8?q?=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponController.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/Controller/CouponController.php b/app/Controller/CouponController.php index 5585fba..f91e2ba 100644 --- a/app/Controller/CouponController.php +++ b/app/Controller/CouponController.php @@ -159,16 +159,16 @@ class CouponController extends BaseController foreach ($coupons as $key => $coupon) { //拼接满减文字提示 - $coupon->full_amount = '满' . $coupon->full_amount . "可用"; + $coupon->full_amount_text = '满' . $coupon->full_amount . "可用"; //判断是折扣优惠券还是满减优惠券 if($coupon->discount_type == 1){ - $coupon->discounts = '¥'.$coupon->discounts; + $coupon->discounts_text = '¥'.$coupon->discounts; }elseif($coupon->discount_type == 2){ - $coupon->discounts = floatval($coupon->discounts)."折"; + $coupon->discounts_text = floatval($coupon->discounts)."折"; } //失效时间格式转换 $usable_end_time = date('Y-m-d H:i:s',$coupon->usable_end_time); - $coupon->usable_end_time = '有效期至:'.$usable_end_time; + $coupon->usable_end_time_text = '有效期至:'.$usable_end_time; if ($coupon->usable_end_time < $nowTime || $coupon->number_remain <= 0) { $expired[] = $coupon; From c0ac902090e7e93af78b3f18ef7ad9af07696c1e Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Wed, 12 Aug 2020 09:49:34 +0800 Subject: [PATCH 095/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E6=B7=BB=E5=8A=A0=E6=B4=BB?= =?UTF-8?q?=E5=8A=A8=E8=BF=87=E6=9C=9F=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 8d27c16..c907186 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -42,7 +42,7 @@ class CouponRebateService implements CouponRebateServiceInterface // status: 0领取成功 >0领取失败 $result = [ 'status' => 1, - 'coupon_text' => '继续努力~' + 'coupon_text' => '活动已过期~' ]; // 错误日志记录 From 7f51e5f0cf08b28d5e4ada213e593c001e5cddf4 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Wed, 12 Aug 2020 11:17:56 +0800 Subject: [PATCH 096/172] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponRebateController.php | 3 +- app/Request/UserRequest.php | 42 +++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 app/Request/UserRequest.php diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 3f4064b..8570a46 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -23,6 +23,7 @@ use App\Model\CouponRec; use App\Request\CouponRebateReceiveRequest; use App\Service\CouponRebateService; use App\Request\CouponRebateTieRequest; +use App\Request\UserRequest; class CouponRebateController extends BaseController { @@ -35,7 +36,7 @@ class CouponRebateController extends BaseController /** * 用户是否领取过领取优惠券 */ - public function isCouponRebate() + public function isCouponRebate(UserRequest $validator) { $user_id = $this->request->input('user_id', 0); $res = $this->CouponRebateService->isCouponRebate($user_id); diff --git a/app/Request/UserRequest.php b/app/Request/UserRequest.php new file mode 100644 index 0000000..2eed8d4 --- /dev/null +++ b/app/Request/UserRequest.php @@ -0,0 +1,42 @@ + 'required|nonempty|integer|exists:ims_cjdc_user,id', + ]; + } + + public function messages(): array + { + return [ + 'user_id.*' => ':attribute信息不正确', + ]; + } + + public function attributes(): array + { + return [ + 'user_id' => '用户', + ]; + } +} From 1ad034cc2c785017349547215decec25a2770981 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Wed, 12 Aug 2020 11:33:13 +0800 Subject: [PATCH 097/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E8=AF=B7=E6=B1=82=E5=8F=82?= =?UTF-8?q?=E6=95=B0ids=E4=B8=BA=E7=A9=BA=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Request/CouponRebateReceiveRequest.php | 3 --- app/Service/CommonService.php | 25 ++++++++++++++++++++++ app/Service/CouponRebateService.php | 19 +++++++++++++--- 3 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 app/Service/CommonService.php diff --git a/app/Request/CouponRebateReceiveRequest.php b/app/Request/CouponRebateReceiveRequest.php index 4c4beed..7abce7d 100644 --- a/app/Request/CouponRebateReceiveRequest.php +++ b/app/Request/CouponRebateReceiveRequest.php @@ -24,7 +24,6 @@ class CouponRebateReceiveRequest extends FormRequest return [ 'user_id' => 'required|nonempty|integer|exists_enable:ims_cjdc_user,id', 'receive_type' => 'required|nonempty|integer', - 'ids' => 'required|nonempty', ]; } @@ -33,7 +32,6 @@ class CouponRebateReceiveRequest extends FormRequest return [ 'user_id.*' => ':attribute信息不正确', 'receive_type.*' => ':attribute必须', - 'ids.*' => ':attribute必须', ]; } @@ -42,7 +40,6 @@ class CouponRebateReceiveRequest extends FormRequest return [ 'user_id' => '领取用户ID', 'receive_type' => '领取方式', - 'ids' => '优惠券', ]; } } diff --git a/app/Service/CommonService.php b/app/Service/CommonService.php new file mode 100644 index 0000000..9ffb169 --- /dev/null +++ b/app/Service/CommonService.php @@ -0,0 +1,25 @@ +0领取失败 $result = [ 'status' => 1, 'coupon_text' => '活动已过期~' ]; + /* 如果请求的优惠券ids为空,则返回过期提示 */ + if($this->commonService->empty($params["ids"])){ + return $result; + } + + $ids = $params["ids"]; + $idsData = is_array($ids) ? $ids : explode(',',$ids); // 错误日志记录 $errorData = [ @@ -150,7 +163,7 @@ class CouponRebateService implements CouponRebateServiceInterface } if(count($receiveSsdb) > 0){ -; + $saveSsdb = [ $ssdbKey, implode(',',$receiveSsdb) From 5ef2076b7402b8d64d3cb7c5d422bef43422aa43 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 11:49:24 +0800 Subject: [PATCH 098/172] =?UTF-8?q?=E5=A4=96=E5=8D=96=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E4=B8=8B=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 10 + app/Controller/OrderController.php | 23 + app/Controller/PaymentController.php | 10 + app/Libs/MQTTClient.php | 1098 ++++++++++++++++++++++++ app/Middleware/Auth/ApiMiddleware.php | 2 +- app/Model/Coupon.php | 3 + app/Model/CouponUserRec.php | 10 + app/Model/CouponUserUse.php | 10 + app/Model/Goods.php | 12 + app/Model/Order.php | 11 + app/Model/OrderGoods.php | 8 + app/Model/OrderMain.php | 81 ++ app/Model/SpecCombination.php | 17 + app/Request/OrderOnlineRequest.php | 72 ++ app/Service/CoupnoServiceInterface.php | 20 + app/Service/CouponService.php | 85 ++ app/Service/OrderService.php | 423 +++++++++ app/Service/OrderServiceInterface.php | 29 + app/TaskWorker/MQTTClientTask.php | 27 + composer.json | 5 +- config/autoload/dependencies.php | 4 +- config/autoload/server.php | 3 - config/autoload/snowflake.php | 24 + config/routes.php | 1 + 24 files changed, 1982 insertions(+), 6 deletions(-) create mode 100644 app/Controller/NotifyController.php create mode 100644 app/Controller/OrderController.php create mode 100644 app/Controller/PaymentController.php create mode 100644 app/Libs/MQTTClient.php create mode 100644 app/Model/CouponUserRec.php create mode 100644 app/Model/CouponUserUse.php create mode 100644 app/Model/Goods.php create mode 100644 app/Model/Order.php create mode 100644 app/Model/OrderGoods.php create mode 100644 app/Model/OrderMain.php create mode 100644 app/Model/SpecCombination.php create mode 100644 app/Request/OrderOnlineRequest.php create mode 100644 app/Service/CoupnoServiceInterface.php create mode 100644 app/Service/CouponService.php create mode 100644 app/Service/OrderService.php create mode 100644 app/Service/OrderServiceInterface.php create mode 100644 app/TaskWorker/MQTTClientTask.php create mode 100644 config/autoload/snowflake.php diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php new file mode 100644 index 0000000..8aa0ba0 --- /dev/null +++ b/app/Controller/NotifyController.php @@ -0,0 +1,10 @@ +orderService->addOnlineOrder($request->validated()); + return $this->success(['order_main_id' => $orderMainId]); + } +} \ No newline at end of file diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php new file mode 100644 index 0000000..86ce06c --- /dev/null +++ b/app/Controller/PaymentController.php @@ -0,0 +1,10 @@ +setConnection($address, $port, $protocol)) { + ; + } + $this->packetId = rand(1,100)*100; // Reduce risk of creating duplicate ids in sequential sessions + } + + /** + * Class destructor - Close socket + */ + function __destruct(){ + $this->close(); + } + + /** + * Setup conection parameters + * + * @param string $address + * @param string $port + * @param string $protocol + * @return boolean If return false then using default parameters where validation failed + */ + function setConnection($address, $port=null, $protocol='tcp'){ + $this->serverAddress = $address; + $this->serverPort = $port; + + // Validate protocol + $protocol = strtolower($protocol); + if (($protocol != 'tcp') && !self::isEncryptionProtocol($protocol)) { + $this->debugMessage('Invalid protocol ('.$protocol.'). Setting to default (tcp).'); + $this->protocol = 'tcp'; + return false; + } + $this->protocol = $protocol; + + return true; + } + + /** + * Build url for connecting to stream + * + * @return string + */ + private function getUrl() { + $url = ''; + if ($this->protocol) $url .= $this->protocol .'://'; + $url .= $this->serverAddress; + if ($this->serverPort) $url .= ':'. $this->serverPort; + return $url; + } + + /** + * Check if encryption protocol is supported + * + * @param string $protcol + * @return boolean + */ + private static function isEncryptionProtocol($protocol) { + return in_array(strtolower($protocol), ['ssl', 'tls', 'tlsv1.0', 'tlsv1.1', 'tlsv1.2', 'sslv3']); + } + + /** + * Sets server certificate and protocol for ssl/tls encryption + * + * @param string $caFile CA file to identify server + * @param string $protocl Crypto protocol (See http://php.net/manual/en/migration56.openssl.php) + * @return boolean False if settings failed, else true + */ + public function setEncryption($caFile, $protocol = null) { + if (file_exists($caFile)) { + $this->caFile = $caFile; + } else { + $this->debugMessage('CA file not found'); + return false; + } + if(self::isEncryptionProtocol($protocol)) { + $this->protocol = $protocol; + } else if (!is_null($protocol)) { + $this->debugMessage('Unknown encryption protocol'); + return false; + } + return true; + } + + /** + * Sets client crt and key files for client-side authentication + * + * @param string $crtFile Client certificate file + * @param string $keyFile Client key file + * @return boolean False if settings failed, else true + */ + public function setClientEncryption($certificateFile, $keyFile) { + if (!file_exists($certificateFile)) { + $this->debugMessage('Client certificate file not found'); + return false; + } + if (!file_exists($keyFile)) { + $this->debugMessage('Client key file not found'); + return false; + } + $this->localCert= $certificateFile; + $this->localPrivateKey = $keyFile; + return true; + } + + /** + * Set authentication details to be used when connecting + * + * @param string $username Username + * @param string $password Password + */ + public function setAuthentication($username, $password) { + $this->connectUsername= $username; + $this->connectPassword = $password; + } + + /** + * Set will (last message defined by MQTT) to send when connection is lost + * + * @param string $topic + * @param string $message + * @param integer $qos + * @param boolean $retain + */ + public function setWill($topic, $message, $qos=1, $retain=false) { + $this->connectWill = true; + $this->connectWillQos = $qos; + $this->connectWillRetain = $retain; + $this->willTopic = $topic; + $this->willMessage = $message; + } + + /** + * Connect to MQTT server + * + * @param string $clientId Unique id used by the server to identify the client + * @param boolean $cleanSession Set true to clear session on server, ie queued messages are purged (not recieved) + * @param integer $keepAlive Number of seconds a connection is considered to be alive without traffic + * @param integer $timeout Number of millliseconds before timeout when reading from socket + * @return boolean Returns false if connection failed + */ + public function sendConnect($clientId, $cleanSession=false, $keepAlive=10, $timeout=5000) { + if (!$this->serverAddress) return false; + + // Basic validation of clientid + // Note: A MQTT server may accept other chars and more than 23 chars in the clientid but that is optional, + // all chars below up to 23 chars are required to be accepted (see section "3.1.3.1 Client Identifier" of the standard) + if(preg_match("/[^0-9a-zA-Z]/",$clientId)) { + $this->debugMessage('ClientId can only contain characters 0-9,a-z,A-Z'); + return false; + } + if(strlen($clientId) > 23) { + $this->debugMessage('ClientId max length is 23 characters/numbers'); + return false; + } + $this->clientId = $clientId; + + $this->connectCleanSession = $cleanSession; + $this->connectKeepAlive = $keepAlive; + $this->socketTimeout = $timeout; + + // Setup certificates if encryption protocol selected + if ($this->isEncryptionProtocol($this->protocol)) { + $mozillaCiphers = implode(':', array( + 'ECDHE-RSA-AES128-GCM-SHA256', + 'ECDHE-ECDSA-AES128-GCM-SHA256', + 'ECDHE-RSA-AES256-GCM-SHA384', + 'ECDHE-ECDSA-AES256-GCM-SHA384', + 'DHE-RSA-AES128-GCM-SHA256', + 'DHE-DSS-AES128-GCM-SHA256', + 'kEDH+AESGCM', + 'ECDHE-RSA-AES128-SHA256', + 'ECDHE-ECDSA-AES128-SHA256', + 'ECDHE-RSA-AES128-SHA', + 'ECDHE-ECDSA-AES128-SHA', + 'ECDHE-RSA-AES256-SHA384', + 'ECDHE-ECDSA-AES256-SHA384', + 'ECDHE-RSA-AES256-SHA', + 'ECDHE-ECDSA-AES256-SHA', + 'DHE-RSA-AES128-SHA256', + 'DHE-RSA-AES128-SHA', + 'DHE-DSS-AES128-SHA256', + 'DHE-RSA-AES256-SHA256', + 'DHE-DSS-AES256-SHA', + 'DHE-RSA-AES256-SHA', + 'AES128-GCM-SHA256', + 'AES256-GCM-SHA384', + 'ECDHE-RSA-RC4-SHA', + 'ECDHE-ECDSA-RC4-SHA', + 'AES128', + 'AES256', + 'RC4-SHA', + 'HIGH', + '!aNULL', + '!eNULL', + '!EXPORT', + '!DES', + '!3DES', + '!MD5', + '!PSK' + )); + // Secure socket communication with these parameters, a ca-file is required + $options = []; + $options['verify_peer'] = true; + $options['verify_peer_name'] = true; + $options['verify_depth'] = 5; + $options['disable_compression'] = true; + $options['SNI_enabled'] = true; + $options['ciphers'] = $mozillaCiphers; + if($this->caFile) { + $options['cafile'] = $this->caFile; + } + if($this->localCert) { + $options['local_cert'] = $this->localCert; + if ($this->localPrivateKey) { + $options['local_pk'] = $this->localPrivateKey; + } + } + $socketContext = stream_context_create(['ssl' => $options]); + $this->debugMessage('Settings socket options: '. var_export($options, true)); + } else { + $socketContext = null; + } + + // Try to open socket + try { + $this->debugMessage('Opening socket to: '. $this->getUrl()); + if ($socketContext) { + $this->socket = stream_socket_client($this->getUrl(), $errno, $errstr, 10, STREAM_CLIENT_CONNECT, $socketContext); + } else { + $this->socket = stream_socket_client($this->getUrl(), $errno, $errstr, 10, STREAM_CLIENT_CONNECT); + } + } catch (\ErrorException $error) { + $this->debugMessage('Exception: Could not open stream with error message: '. $error->getMessage()); + $this->socket = null; + return false; + } + + // Check if socket was opened successfully + if ($this->socket === false) { + $this->socket = null; + $this->debugMessage('Connection failed. Error-no:'. $errno .' Error message: '. $errstr); + return false; + } + + // Set socket timeout + ini_set('default_socket_timeout', 10); + stream_set_timeout($this->socket, 0, $this->socketTimeout * 1000); + // Set stream to non-blocking mode, ie do not wait to read if stream is empty + stream_set_blocking($this->socket, true); + + // Calculate connect flags to use in CONNECT header + $connectFlags = 0; + if ($this->connectCleanSession) $connectFlags += 0x02; + if ($this->connectWill) { + $connectFlags += 0x04; + if ($this->connectWillQos) $connectFlags += ($this->connectWill << 3); + if ($this->connectWillRetain) $connectFlags += 0x20; + } + if ($this->connectUsername) { + $connectFlags += 0x80; + if ($this->connectPassword) $connectFlags += 0x40; + } + + // Build payload and header for CONNECT-packet + $payload = chr(0x00).chr(0x04); // MSB & LSB length of MQTT = 4 + $payload .= 'MQTT'; + $payload .= chr(0x04); // Protocol level (3.1.1) + $payload .= chr($connectFlags); // Connect flags + $payload .= chr($this->connectKeepAlive >> 8); // Keepalive (MSB) + $payload .= chr($this->connectKeepAlive & 0xff); // Keepalive (LSB) + if ($this->connectCleanSession && empty($this->clientId)) { + $this->clientId = rand(1,999999999); + } + if ($this->clientId) { + $payload .= $this->createPayload($this->clientId); + } + if($this->connectWill){ + $payload .= $this->createPayload($this->willTopic); + $payload .= $this->createPayload($this->willMessage); + } + if($this->connectUsername) { + $payload .= $this->createPayload($this->connectUsername); + } + if ($this->connectPassword) { + $payload .= $this->createPayload($this->connectPassword); + } + $header = $this->createHeader(self::MQTT_CONNECT, $payload); + $this->debugMessage('Sending CONNECT'); + $this->send($header . $payload); + + // Wait for CONNACK packet + $response = $this->waitForPacket(self::MQTT_CONNACK); + if($response !== false && ($response[2] == chr(0))) { + $this->debugMessage('Connected to MQTT'); + $this->lastConnectResult = 0; + return true; + } else { + $this->debugMessage('Connection failed! Error: '. ord($response[2])); + $this->lastConnectResult = ord($response[2]); + $this->close(); + return false; + } + } + + /** + * Publish a topic and message (QoS 0,1,2 supported) + * + * @param string $topic + * @param string $message + * @param byte $qos + * @return boolean + */ + public function sendPublish($topic, $message, $qos = self::MQTT_QOS1, $retain = 0) { + if(!$this->isConnected()) return false; + + if($qos!=self::MQTT_QOS0 && $qos!=self::MQTT_QOS1 && $qos!=self::MQTT_QOS2) return false; + + $packetId = $this->getNextPacketId(); + $payload = $this->createPayload($topic); + if($qos >= self::MQTT_QOS1) { + // Packet identifier required for QoS level >= 1 + $payload .= $this->getPacketIdPayload(); + } + $payload .= $message; + + $dupFlag = 0; + $header = $this->createHeader(self::MQTT_PUBLISH + ($dupFlag<<3) + ($qos<<1) + $retain, $payload); + $this->debugMessage('Sending PUBLISH'); + $this->send($header . $payload); + + if($qos == self::MQTT_QOS1) { + // If QoS level 1, only a PUBACK packet is expected + $response = $this->waitForPacket(self::MQTT_PUBACK, $packetId); + if($response === false) { + $this->debugMessage('Packet missing, expecting PUBACK'); + return false; + } + } elseif($qos == self::MQTT_QOS2) { + // If QoS level 2, a PUBREC packet is expected + $response = $this->waitForPacket(self::MQTT_PUBREC, $packetId); + if($response === false) { + $this->debugMessage('Packet missing, expecting PUBREC'); + return false; + } + + // Send PUBREL + $response = $this->sendPubRel($packetId); + if($response === false) { + $this->debugMessage('Failed to send PUBREL'); + return false; + } + + // A PUBCOMP packet is expected + $response = $this->waitForPacket(self::MQTT_PUBCOMP, $packetId); + if($response === false) { + $this->debugMessage('Packet missing, expecting PUBCOMP'); + return false; + } + } + + return true; + } + + /** + * Send PUBACK as response to a recieved PUBLISH packet (QoS Level 1) + * + * @param integer $packetId Packet identifier of PUBLISH packet + * @return boolean Returns true if packet sent successfully + */ + public function sendPubAck($packetId) { + if(!$this->isConnected()) return false; + + $payload = chr(($packetId & 0xff00)>>8) . chr($packetId & 0xff); + $header = $this->createHeader(self::MQTT_PUBACK, $payload); + $this->debugMessage('Sending PUBACK'); + $this->send($header . $payload); + + return true; + } + + /** + * Send PUBREC as response to a recieved PUBLISH packet (QoS Level 2) + * + * @param integer $packetId Packet identifier of PUBLISH packet + * @return boolean Returns true if packet sent successfully + */ + public function sendPubRec($packetId) { + if(!$this->isConnected()) return false; + + $payload = chr(($packetId & 0xff00)>>8) . chr($packetId & 0xff); + $header = $this->createHeader(self::MQTT_PUBREC, $payload); + $this->debugMessage('Sending PUBREC'); + $this->send($header . $payload); + + return true; + } + + /** + * Send PUBREL as response to a recieved PUBREC packet (QoS Level 2) + * + * @param integer $packetId Packet identifier of PUBLISH packet + * @return boolean Returns true if packet sent successfully + */ + public function sendPubRel($packetId) { + if(!$this->isConnected()) return false; + + $payload = chr(($packetId & 0xff00)>>8) . chr($packetId & 0xff); + $header = $this->createHeader(self::MQTT_PUBREL, $payload); + $this->debugMessage('Sending PUBREL'); + $this->send($header . $payload); + + return true; + } + + /** + * Send PUBCOMP as response to a recieved PUBREL packet (QoS Level 2) + * + * @param integer $packetId Packet identifier of PUBLISH packet + * @return boolean Returns true if packet sent successfully + */ + public function sendPubComp($packetId) { + if(!$this->isConnected()) return false; + + $payload = chr(($packetId & 0xff00)>>8) . chr($packetId & 0xff); + $header = $this->createHeader(self::MQTT_PUBCOMP, $payload); + $this->debugMessage('Sending PUBCOMP'); + $this->send($header . $payload); + + return true; + } + + /** + * Subscribe to topics with a quality of service + * + * @param string[] $topics Topics to subscribe for + * @param integer $qos Quality of serivce for all topics + * @return boolean Returns true if SUBACK was recieved + */ + public function sendSubscribe($topics, $qos = self::MQTT_QOS1) { + if (!is_array($topics)) $topics = [$topics]; + if(!$this->isConnected()) return false; + + $packetId = $this->getNextPacketId(); + $payload = $this->getPacketIdPayload(); + foreach($topics as $topic) { + $payload .= $this->createPayload($topic); + $payload .= chr($qos); + } + $header = $this->createHeader(self::MQTT_SUBSCRIBE + 0x02, $payload); + $this->debugMessage('Sending SUBSCRIBE'); + $this->send($header . $payload); + + // A SUBACK packet is expected + $response = $this->waitForPacket(self::MQTT_SUBACK, $packetId); + if($response === false) { + $this->debugMessage('Packet missing, expecting SUBACK'); + return false; + } + $responsePayload = substr($response, 3); // skip header and identifier (3 bytes) + if (strlen($responsePayload) != count($topics)) { + $this->debugMessage('Did not recieve SUBACK for all topics'); + return false; + } + + // Check which subscriptions that were approved + $topicsResult = []; + $i = 0; + foreach ($topics as $topic) { + $topicsResult[$topic] = []; + if ($responsePayload[$i] > 0x02) { + $topicsResult[$topic]['success'] = false; + $topicsResult[$topic]['qosGiven'] = null; + } else { + $topicsResult[$topic]['success'] = true; + $topicsResult[$topic]['qosGiven'] = (int) ord($responsePayload[$i]); + } + $i++; + } + + return $topicsResult; + } + + /** + * Send unsubscribe packet for given topics + * + * @param string[] $topics + * @return boolean Returns true if UNSUBACK was recieved + */ + public function sendUnsubscribe($topics) { + if(!$this->isConnected()) return false; + + $packetId = $this->getNextPacketId(); + $payload = $this->getPacketIdPayload(); + foreach($topics as $topic) { + $payload .= $this->createPayload($topic); + } + $header = $this->createHeader(self::MQTT_UNSUBSCRIBE + 0x02, $payload); + $this->debugMessage('Sending UNSUBSCRIBE'); + $this->send($header . $payload); + + // An UNSUBACK packet is expected + $response = $this->waitForPacket(self::MQTT_UNSUBACK, $packetId); + if($response === false) { + $this->debugMessage('Invalid packet received, expecting UNSUBACK'); + return false; + } + return true; + } + + /** + * Sends PINGREQ packet to server + * + * @return boolean Returns true if PINGRESP was recieved + */ + public function sendPing() { + if(!$this->isConnected()) return false; + + $this->timeSincePingReq = time(); + $header = $this->createHeader(self::MQTT_PINGREQ); + $this->debugMessage('Sending PING'); + $this->send($header); + $this->pingReqTime = time(); + + // A PINGRESP packet is expected + $response = $this->waitForPacket(self::MQTT_PINGRESP); + if($response === false) { + $this->debugMessage('Invalid packet received, expecting PINGRESP'); + return false; + } + + return true; + } + + /** + * Send disconnect and close socket + */ + public function sendDisconnect() { + if($this->isConnected()) { + $header = $this->createHeader(self::MQTT_DISCONNECT); + $this->debugMessage('Sending DISCONNECT'); + $this->send($header); + $this->close(); + } + } + + /** + * Close socket + */ + public function close() { + if($this->isConnected()) { + $this->debugMessage('Closing socket'); + stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR); + $this->socket = null; + $this->serverAliveTime = null; + } + } + + /** + * Check if connected to stream + * @return boolean + */ + public function isConnected() { + return !empty($this->socket); + } + + /** + * Check if connection is alive + * @return boolean + */ + public function isAlive() { + return $this->isConnected() && ($this->serverAliveTime + $this->connectKeepAlive <= time()); + } + + /** + * Set debug mode, if true then output progress messages + * + * @param boolean $mode + */ + public function setDebug($mode = true) { + $this->debug = $mode; + } + + /** + * Print message to console if debug mode is on + * + * @param string $message + */ + private function debugMessage($message) { + if ($this->debug) { + echo 'MQTT: '. $message .PHP_EOL; + } + } + + /** + * Return next packet identifier to use in MQTT packet + * Max 2 bytes to be used, restart on 0 if end reached + * + * @return integer + */ + private function getNextPacketId() { + return ($this->packetId = ($this->packetId + 1) & 0xffff); + } + + /** + * Return payload of packet id, use latest generated packet id as default + * + * @param integer $packetId + * @return string Two chars with apyload to add in MQTT-message + */ + private function getPacketIdPayload($packetId = null) { + if (empty($packetId)) $packetId = $this->packetId; + return chr(($packetId & 0xff00)>>8) . chr($packetId & 0xff); + } + + /** + * Add payload length as bytes to begining of string and return + * + * @param string $payload + * @return string + */ + private function createPayload($payload) { + $fullLength = strlen($payload); + $retval = chr($fullLength>>8).chr($fullLength&0xff).$payload; + return $retval; + } + + /** + * Decode payload using inital length (2 bytes) and return as string array + * + * @param string $payload + * @return string[] + */ + private function decodePayload($payload) { + $result = []; + while (strlen($payload) >= 2) { + $length = ord($payload[0])<<8 + ord($payload[1]); + if (strlen($payload) <= $length + 2) { + $result[] = substr($payload, 2, $length); + } + $payload = substr($payload, min($length + 2, strlen($payload))); + } + return $result; + } + + /** + * Send data to open socket + * + * @param string $data + * @return boolean Only returns true if all data was sent + */ + private function send($data) { + if ($this->socket) { + $result = fwrite($this->socket, $data); + if (($result !== false) && ($result == strlen($data))) { + $this->serverAliveTime = time(); + return true; + } + } + return false; + } + + /** + * Read bytes from socket until x bytes read, eof reached or socket timeout + * + * @param int $bytes Number of bytes to read + * @return string Return bytes read as a string + */ + private function readBytes($bytes) { + if (!$this->socket) return false; + //if ($bytes == 0) return ''; + $bytesLeft = $bytes; + $result = ''; + do { + // If stream at end, close down socket and exit + if(feof($this->socket)) { + $this->debugMessage('Reached EOF for stream'); + $this->close(); + return $result; + } + // Try to read from stream + $str = fread($this->socket, $bytesLeft); + if ($str !== false && strlen($str) > 0) { + $result .= $str; + $bytesLeft -= strlen($str); + } + if ($bytesLeft <= 0) { + // If all bytes read, then return them + $this->serverAliveTime = time(); + return $result; + } + // Check if timeout + $info = stream_get_meta_data($this->socket); + if ($info['timed_out']) { + $this->debugMessage('Read timeout'); + return false; + } + // Wait a while before trying to read again (in micro seconds) + usleep($this->socketReadDelay * 1000); + } while (true); + } + + /** + * Encode length to bytes to send in stream + * + * @param integer $len + * @return string + */ + private function encodeLength($len) { + if ($len < 0 || $len >= 128*128*128*128) { + // illegal length + return false; + } + $output = ''; + do { + $byte = $len & 0x7f; // keep lowest 7 bits + $len = $len >> 7; // shift away lowest 7 bits + if ($len > 0) { + $byte = $byte | 0x80; // set high bit to indicate continuation + } + $output .= chr($byte); + } while ($len > 0); + return $output; + } + + /** + * Return length of packet by reading from stream + * + * @return integer + */ + private function readPacketLength() { + $bytesRead = 0; + $len = 0; + $multiplier = 1; + do { + if ($bytesRead > 4) { + return false; // Malformed length + } + $str = $this->readBytes(1); + if ($str === false || strlen($str) != 1) { + return false; // Unexpected end of stream + } + $byte = ord($str[0]); + $len += ($byte & 0x7f) * $multiplier; + $isContinued = ($byte & 0x80); + if ($isContinued) { + $multiplier *= 128; + } + $bytesRead++; + } while ($isContinued); + return $len; + } + + /** + * Create MQTT header from command and payload + * + * @param int $command Command to send + * @param string $payload Payload to be sent + * + * @return string Header to send + */ + private function createHeader($command, $payload = '') { + return chr($command) . $this->encodeLength(strlen($payload)); + } + + /** + * Read next packet from stream + * + * @return boolean + */ + private function readNextPacket() { + do { + $header = $this->readBytes(1); + if ($header === false) { + $this->lastReadStatus = self::READ_STATUS_ERROR_HEADER; + return false; + } + } while ((ord($header)&0xf0) == 0); // 0 is illegal control code to start with + + $packetLength = $this->readPacketLength(); + if ($packetLength === false) { + $this->debugMessage('Could not decode packet length'); + $this->lastReadStatus = self::READ_STATUS_ERROR_PACKETLENGTH; + return false; + } + + $payload = $packetLength > 0 ? $this->readBytes($packetLength) : ''; + if ($payload === false) { + $this->lastReadStatus = self::READ_STATUS_ERROR_PAYLOAD; + return false; + } + $this->debugMessage('Packet response: '. self::str2hex($header . $payload)); + $this->lastReadStatus = self::READ_STATUS_OK; + return $header . $payload; + } + + public function getLastReadStatus() { + return $this->lastReadStatus; + } + + public function hasMoreToRead() { + return ($this->lastReadStatus == self::READ_STATUS_OK) && $this->isConnected(); + } + + /** + * Read packets from stream and save to queue. Quit after x packets or timeout. + * + * @param integer $maxPackets Packet id the message must match + * @return integer Number of packets read + */ + private function readPackets($maxPackets = 100) { + $receivedPackets = 0; + while (($receivedPackets < $maxPackets) && ($packet = $this->readNextPacket()) !== false) { + $this->packetQueue[] = $packet; + $receivedPackets++; + } + return $receivedPackets; + } + + /** + * Wait until a certain packet is found in the stream. + * Save other recieved packets in queue. + * + * @param byte $header Header to look for (only 4 high bits) 0xf0 + * @param integer $verifyPacketId Packet id the message must match + * @return boolean + */ + private function waitForPacket($header, $verifyPacketId = false) { + // first check unhandled packets + foreach ($this->packetQueue as $key => $packet) { + if ($this->isPacketVerified($packet, $header, $verifyPacketId)) { + // if found, remove from queue and return packet + unset($this->packetQueue[$key]); + return $packet; + } + } + // if not found in queue, start reading from stream until found or timeout + do { + $packet = $this->readNextPacket(); + if ($packet === false || empty($packet)) return false; + if ($this->isPacketVerified($packet, $header, $verifyPacketId)) { + return $packet; + } + // another packet found, save it to queue + $this->packetQueue[] = $packet; + } while(true); + } + + /** + * Check if packet is of a given type and packet id match latest sent packet id + * + * @param string $packet + * @param char $header + * @param integer $verifyPacketId + * @return boolean + */ + private function isPacketVerified($packet, $header, $verifyPacketId = false) { + if (is_string($packet) && strlen($packet) >= 1) { + if ((int)(ord($packet[0])&0xf0) == (int)($header&0xf0)) { + if ($verifyPacketId === false) return true; + if (strlen($packet) >= 3) { + $receivedPacketId = (int)(ord($packet[1])<<8) + ord($packet[2]); + if($verifyPacketId == $receivedPacketId) { + return true; + } + } + } + } + return false; + } + + /** + * Get packets matching a header from the queue and remove from queue + * + * @param char $header + * @return string[] + */ + public function getQueuePackets($header) { + $foundPackets = []; + foreach ($this->packetQueue as $key => $packet) { + if ($this->isPacketVerified($packet, $header)) { + $foundPackets[] = $packet; + unset($this->packetQueue[$key]); + } + } + return $foundPackets; + } + + /** + * Get PUBLISH packets and return them as messages + * + * @param integer $maxMessages Max messages to read + * @param boolean $sendPubAck If true, then send PUBACK to MQTT-server (QoS 1) + * @param boolean $sendPubRec If true, then send PUBREC to MQTT-server, wait for PUBREL and send PUBCOMP (QoS 2) + * @return string[] All PUBLISH messages which were confirmed or no confirmation needed/wanted + */ + public function getPublishMessages($maxMessages = 100, $sendPubAck = false, $sendPubRec = false) { + $packetsRead = $this->readPackets($maxMessages); + $packets = $this->getQueuePackets(self::MQTT_PUBLISH); + $messages = []; + foreach ($packets as $key => $packet) { + $message = $this->decodePublish($packet); + if ($message === false) { + $this->debugMessage('Message could not be decoded'); + continue; + } + + if ($sendPubAck && ($message['qos'] == self::MQTT_QOS1)) { + if($this->sendPubAck($message['packetId']) === false) { + $this->debugMessage('Failed to send PUBACK'); + continue; + } + } elseif ($sendPubRec && ($message['qos'] == self::MQTT_QOS2)) { + // Send PUBREC + if($this->sendPubRec($message['packetId']) === false) { + $this->debugMessage('Failed to send PUBREC'); + continue; + } + // A PUBREL packet is expected + $response = $this->waitForPacket(self::MQTT_PUBREL, $message['packetId']); + if($response === false) { + $this->debugMessage('Packet missing, expecting PUBREL'); + continue; + } + // Send PUBCOMP + if($this->sendPubComp($message['packetId']) === false) { + $this->debugMessage('Failed to send PUBCOMP'); + continue; + } + } + + // Package was successfully confirmed or no confirmation needed/wanted --> store it + $messages[] = $message; + } + return $messages; + } + + /** + * Decode a publish packet to its attributes + * + * @param string $packet + * @return array|boolean Return message or false if decode failed + */ + public function decodePublish($packet) { + if (!is_string($packet) || (strlen($packet) <= 3)) { + return false; + } + $flags = ord($packet[0]) & 0x0f; + $duplicate = ($flags == 0x80); + $retain = ($flags == 0x01); + $qos = ($flags>>1) & 0x03; + $topicLength = (ord($packet[1])<<8) + ord($packet[2]); + $topic = substr($packet, 3, $topicLength); + + $payload = substr($packet, 3 + $topicLength); // Get the payload of the packet + if ($qos == 0) { + // no packet id for QoS 0, the payload is the message + $message = $payload; + $packetId = NULL; + } else { + if (strlen($payload) >= 2) { + $packetId = (ord($payload[0])<<8) + ord($payload[1]); + $message = substr($payload, 2); // skip packet id (2 bytes) for QoS 1 and 2 + } else { + // 2 byte packet id required, but not found. exit gracefully (no failure) + $packetId = NULL; + $message = ''; + } + } + return [ + 'topic' => self::convertActiveMqTopic($topic), + 'message' => $message, + 'retain' => $retain, + 'duplicate' => $duplicate, + 'qos' => $qos, + 'packetId' => $packetId, + ]; + } + + /** + * Replace ActiveMQ special characters to MQTT-standard + * + * @param string $topic + * @return string + */ + private static function convertActiveMqTopic($topic) { + $topic = str_replace(".","/", $topic); + $topic = str_replace("*","+", $topic); + $topic = str_replace(">","#", $topic); + return $topic; + } + + /** + * Return a string interpreted as hex and ASCII (between 0x20-0x7f) + * Good for displaying recieved packets + * + * @param string $str + * @return string + */ + private function str2hex($str) { + $hex = ''; + $ascii = ''; + for ($i=0; $i= 0x20 && ord($char) <= 0x7f) { + $ascii .= $char; + } else { + $ascii .= '.'; + } + $hex .= dechex(ord($char)).' '; + } + return $hex . '"'. $ascii .'"'; + } + + public function dumpQueue() { + foreach ($this->packetQueue as $packet) { + $this->str2hex($packet) . PHP_EOL; + } + } +} \ No newline at end of file diff --git a/app/Middleware/Auth/ApiMiddleware.php b/app/Middleware/Auth/ApiMiddleware.php index ce06bff..44cf3fc 100644 --- a/app/Middleware/Auth/ApiMiddleware.php +++ b/app/Middleware/Auth/ApiMiddleware.php @@ -39,7 +39,7 @@ class ApiMiddleware implements MiddlewareInterface public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { - if (env('APP_ENV') == 'dev') { + if (env('APP_ENV') == 'dev' || env('APP_ENV') == 'local') { return $handler->handle($request); } diff --git a/app/Model/Coupon.php b/app/Model/Coupon.php index b6d984d..e50574b 100644 --- a/app/Model/Coupon.php +++ b/app/Model/Coupon.php @@ -6,6 +6,9 @@ use App\Model\Model; class Coupon extends Model { + const DISCOUNT_TYPE_CASH = 1; + const DISCOUNT_TYPE_RATE = 2; + protected $table = 'ims_system_coupon_user'; } diff --git a/app/Model/CouponUserRec.php b/app/Model/CouponUserRec.php new file mode 100644 index 0000000..c5c2608 --- /dev/null +++ b/app/Model/CouponUserRec.php @@ -0,0 +1,10 @@ +belongsTo(Goods::class, 'good_id', 'id'); + } + +} \ No newline at end of file diff --git a/app/Request/OrderOnlineRequest.php b/app/Request/OrderOnlineRequest.php new file mode 100644 index 0000000..dfe0ae6 --- /dev/null +++ b/app/Request/OrderOnlineRequest.php @@ -0,0 +1,72 @@ + 'nonempty', + 'delivery_no' => '', + 'dada_fee' => 'nonempty', + 'market_id' => 'required|nonempty|integer', + 'user_id' => 'required|nonempty|integer', + 'money' => 'required|nonempty', + 'box_money' => '', + 'ps_money' => '', + 'mj_money' => '', + 'xyh_money' => '', + 'yhq_money' => '', + 'yhq_money2' => '', + 'zk_money' => '', + 'tel' => 'required|nonempty', + 'name' => 'required|nonempty', + 'address' => 'required|nonempty', + 'area' => '', + 'lat' => 'required|nonempty', + 'lng' => 'required|nonempty', + 'note' => '', + 'type' => 'required|nonempty', + 'form_id' => '', + 'form_id2' => '', + 'delivery_time' => '', + 'order_type' => 'nonempty', + 'pay_type' => 'nonempty', + 'coupon_id' => '', + 'coupon_id2' => '', + 'uniacid' => 'nonempty', + 'store_list' => 'nonempty', + 'receive_coupon_ids' => '', + ]; + } + + public function messages(): array + { + return [ + '*.*' => ':attribute 参数异常' + ]; + } + + public function attributes(): array + { + return [ + + ]; + } +} diff --git a/app/Service/CoupnoServiceInterface.php b/app/Service/CoupnoServiceInterface.php new file mode 100644 index 0000000..4e3d9a4 --- /dev/null +++ b/app/Service/CoupnoServiceInterface.php @@ -0,0 +1,20 @@ +get(Redis::class); + $couponTodayUsedIds = $redis->sMembers('coupon_'.date('Ymd').'_used_'.$userId); + + $currentTime = time(); + + $builder = Db::table('ims_system_coupon_user_receive as receive') + ->join('ims_system_coupon_user as coupon', 'coupon.id', '=', 'receive.system_coupon_user_id', 'inner'); + + if (is_array($fields)&&!empty($fields)) { + $builder->select([ + 'receive.id as receive_id', + 'receive.user_id', + 'receive.number_remain', + 'coupon.id', + 'coupon.title', + 'coupon.full_amount', + 'coupon.discounts', + 'coupon.usable_start_time', + 'coupon.usable_end_time', + 'coupon.discount_type' + ]); + } + + if (is_array($couponTodayUsedIds)&&!empty($couponTodayUsedIds)) { + $builder->whereNotIn('coupon.id', $couponTodayUsedIds); + } + + return $builder->where(['receive.user_id' => $userId]) + ->whereIn('receive.status', [0,1]) + ->where('receive.number_remain', '>', 0) + ->whereIn('coupon.type', [1,$type]) + ->where('coupon.full_amount', '<=', $orderAmount) + ->where('coupon.usable_start_time', '<=', $currentTime) + ->where('coupon.usable_end_time', '>=', $currentTime) + ->where('coupon.usable_number', '<=', Db::raw('receive.number_remain')) + ->where('coupon.market_id', 'in', [0, $marketId]) + ->whereIn('coupon.storetype_id', $storeTypeIds) + ->orderByRaw('coupon.discounts DESC, coupon.full_amount DESC') + ->get() + ->toArray(); + } + + /** + * 缓存优惠券今日使用情况 + * @param $userId + * @param $couponId + * @param $couponRecId + * @return bool + */ + function cacheTodayCouponUsed($userId, $couponId, $couponRecId) + { + + $redis = ApplicationContext::getContainer()->get(Redis::class); + + $setRes = $redis->sAdd( + 'coupon_'.date('Ymd').'_used_'.$userId, + $couponId + ); + + $expireRes = $redis->expire( + 'coupon_'.date('Ymd').'_used_'.$userId, + strtotime(date('Y-m-d').' 23:59:59')-time() + ); + + return $setRes&&$expireRes; + } +} \ No newline at end of file diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php new file mode 100644 index 0000000..e16d2cb --- /dev/null +++ b/app/Service/OrderService.php @@ -0,0 +1,423 @@ +existsByOrderNum($data['order_num'])) { + return $orderMainId; + } + + Db::beginTransaction(); + try { + + // 计算当前订单可用红包优惠金额 + $couponMoney = 0; + if (isset($data['receive_coupon_ids'])&&$data['receive_coupon_ids']) { + $receiveCouponIds = explode(',', str_replace(',',',',$data['receive_coupon_ids'])); + $couponMoney = $this->getCouponAmount($receiveCouponIds, $data['money'], $data['user_id'], $data['market_id']); + } + $dataMain['yhq_money2'] = $couponMoney; + + // 获取分布式全局ID + $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class); + $dataMain['global_order_id'] = $generator->generate(); + + // 店铺IDs + $dataMain['store_ids'] = ''; + $storeList = json_decode(json_encode($data['store_list']), true); + if (!is_array($storeList)||empty($storeList)) { + Db::rollBack(); + return '订单中商品不存在或已失效'; + } + + // 获取商户IDs + foreach ($storeList as &$item) { + $dataMain['store_ids'] .= empty($dataMain['store_ids']) ? $item['store_id'] : ','.$item['store_id']; + } + + // 主订单插入数据 + $currentTime = time(); + $dataMain['time'] = date('Y-m-d H:i:s', $currentTime); + $dataMain['time_add'] = $currentTime; + $dataMain['state'] = OrderMain::ORDER_STATE_UNPAY; + $dataMain['code'] = $dataMain['global_order_id']; + + // 主订单模型保存 + $orderMain = OrderMain::create($dataMain); + $orderMainId = $orderMain->id; + + // 统计订单中所有店铺当日订单数,做店铺订单序号 + $countsArr = Order::query()->select('COUNT(*) AS count, id') + ->whereIn('store_id', explode(',', $dataMain['store_ids'])) + ->where(['type' => OrderMain::ORDER_TYPE_ONLINE]) + ->whereBetween('time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')]) + ->get() + ->toArray(); + + $storeOrderCounts = []; + foreach ($countsArr as $key => &$row) { + $storeOrderCounts[$row['id']] = $row['count']; + } + + // 循环处理订单总额、子订单总额、商品、商户订单等信息 + $orderAmountTotal = 0; # 总订单金额 + foreach ($storeList as $key => &$item) { + + // 子订单数据处理 + $dataChild = [ + 'uniacid' => $data['uniacid'], + 'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999), + 'user_id' => $orderMain->user_id, + 'store_id' => $item['store_id'], + 'order_main_id' => $orderMain, + 'state' => OrderMain::ORDER_STATE_UNPAY, + 'tel' => $orderMain->tel, + 'name' => $orderMain->name, + 'address' => $orderMain->address, + 'area' => $orderMain->area, + 'time' => date("Y-m-d H:i:s"), + 'note' => $item['note'], + 'delivery_time' => $orderMain->delivery_time, + 'type' => $orderMain->type, + 'lat' => $orderMain->lat, + 'lng' => $orderMain->lng, + 'pay_type' => $orderMain->pay_type, + 'order_type' => $orderMain->order_type, + 'money' => floatval($item['subtotal']), + 'box_money' => floatval($item['box_money']), + 'mj_money' => floatval($item['mj_money']), + 'yhq_money' => floatval($item['yhq_money']), + 'yhq_money2' => floatval($item['yhq_money2']), + 'zk_money' => floatval($item['zk_money']), + 'coupon_id' => $item['coupon_id'], + 'coupon_id2' => $item['coupon_id2'], + 'xyh_money' => floatval($item['xyh_money']), + 'oid' => (isset($storeOrderCounts[$item['store_id']]) ? $item['store_id'] : 0) + 1, + 'time_add' => date("Y-m-d H:i:s"), + ]; + + $order = Order::create($dataChild); + $orderChildId = $order->id; + + // 子订单内商品处理 + $goodsAmountTotal = 0; + $orderGoods = []; + if (!is_array($item['good_list'])||empty($item['good_list'])) { + Db::rollBack(); + return '订单商品异常'; + } + foreach ($item['good_list'] as &$goods) { + + $goodsAmount = bcadd(floatval($goods['money']), floatval($goods['box_money'])); + $goodsAmount = bcmul($goodsAmount, $goods['num']); + $goodsAmountTotal = bcadd($goodsAmountTotal, $goodsAmount); + + $orderGoods[$goods['id']] = $goods; + $orderGoods[$goods['id']]['uniacid'] = $data['uniacid']; + $orderGoods[$goods['id']]['order_id'] = $orderChildId; + $orderGoods[$goods['id']]['user_id'] = $dataMain['user_id']; + $orderGoods[$goods['id']]['store_id'] = $item['store_id']; + } + + // 子订单优惠总额 + $discountAmountTotal = bcadd($dataChild['mj_money'], $dataChild['yhq_money']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['yhq_money2']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['zk_money']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['xyh_money']); + + $goodsAmountTotal = bcsub($goodsAmountTotal, $discountAmountTotal, 2); + $orderAmountTotal = bcadd($orderAmountTotal, $goodsAmountTotal, 2); + + // 校验子订单金额 + if ($goodsAmountTotal != $dataChild['money']) { + Db::rollBack(); + return '店铺订单总金额错误'; + } + + } + + // 校验库存 + foreach ($orderGoods as $Key=>&$goodsItem) { + + $goodsItem['combination_id'] = intval($goodsItem['combination_id']); + + // 存在规格,则去规格处查库存,整个接口还有很多别的问题,目前 + $goods = (object)[]; + if ($goodsItem['combination_id'] > 0) { + + $goods = SpecCombination::query() + ->select('id, number AS inventory') + ->where(['id' => $goodsItem['combination_id']]) + ->first(); + $goods->name = $goods->goods->name; + $goods->is_max = $goods->goods->is_max; + + } else { + + $goods = Goods::query() + ->select('id, name, is_max, inventory') + ->where(['id' => $goodsItem['good_id']]) + ->first(); + + } + + if (!$goods) { + Db::rollBack(); + return '缺少商品'; + } + + if($goodsItem['num'] > $goods->inventory && $goods->is_max != Goods::INVENTORY_NOLIMIT){ + Db::rollBack(); + return '商品 '.$goods->name.' 库存不足!'; + } + + } + + // 校验总订单金额 + $deliveryAmount = 0; # 配送费用 + if($dataMain['order_type'] == OrderMain::ORDER_TYPE_ONLINE){ + $deliveryAmount = $dataMain['dada_fee']; + } + + $orderAmountTotal = bcadd($orderAmountTotal, $deliveryAmount); + # 总订单优惠总额 + $discountAmountTotal = bcadd($dataMain['mj_money'], $dataMain['yhq_money']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['yhq_money2']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['zk_money']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['xyh_money']); + $orderAmountTotal = bcsub($orderAmountTotal, $discountAmountTotal, 2); + + if ($orderAmountTotal != bcsub(bcadd($dataMain['money'], $deliveryAmount), $discountAmountTotal, 2)) { + Db::rollBack(); + return '订单总金额错误'; + } + + // 添加订单商品 + $tempGoods = $orderGoods; + $orderGoods = []; + foreach ($tempGoods as $key => &$value) { + $goods['good_id'] = $value['good_id']; + $goods['img'] = $value['logo']; + $goods['number'] = $value['num']; + $goods['order_id'] = $value['order_id']; + $goods['name'] = $value['name']; + $goods['money'] = $value['money']; + $goods['dishes_id'] = $value['dishes_id']; + $goods['spec'] = $value['spec']; + $goods['is_qg'] = $value['is_qg']; + $goods['good_unit'] = $value['good_unit']; + $goods['uniacid'] = $value['uniacid']; + $goods['combination_id'] = $value['combination_id']; + $orderGoods[] = $goods; + } + + $addOrderGoods = OrderGoods::query()->insert($orderGoods); + if (!$addOrderGoods) { + Db::rollBack(); + return '订单商品异常'; + } + + // 修改总订单金额,金额是计算来的 + // TODO 这部分其实可以结合处理优化一下,循环前后关联处理太多 + $updateOrderMain = OrderMain::query()->where(['id' => $orderMainId])->update(['money' => $orderAmountTotal, 'total_money' => $dataMain['money']]); + if (!$updateOrderMain) { + Db::rollBack(); + return '订单总金额记录失败'; + } + + // 处理红包的使用 + $canUseConpons = $this->couponService->getOrderCanUseCoupons( + $data['money'], + $data['market_id'], + $data['user_id'], + [ + 'receive.id', + 'receive.user_id', + 'receive.number', + 'receive.number_remain', + 'receive.system_coupon_user_id', + 'coupon.discounts', + 'coupon.discount_type', + ] + ); + + if (is_array($canUseConpons)&&!empty($canUseConpons)) { + # 使用记录、更新当前优惠券 + foreach ($canUseConpons as $key => &$coupon) { + $couponUse = [ + 'user_id' => $coupon['user_id'], + 'user_receive_id' => $coupon['id'], + 'system_coupon_id' => $coupon['system_coupon_user_id'], + 'order_main_id' => $orderMainId, + 'use_time' => $currentTime, + 'return_time' => 0, + 'number' => 1, + 'status' => 1, + 'update_time' => 0, + ]; + + $insertRes = CouponUserUse::query()->insert($couponUse); + + if ($insertRes) { + $numberRemain = $coupon['number_remain'] - 1; + if ($numberRemain == 0) { + $status = 2; + } elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) { + $status = 1; + } elseif ($numberRemain == $coupon['number']) { + $status = 0; + } + + $upRes = CouponUserRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]); + + if (!$upRes) { + Db::rollBack(); + return '优惠券使用失败'; + } + + // 缓存使用记录 + $usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']); + if (!$usedRes) { + Db::rollBack(); + return '优惠券使用失败'; + } + + } else { + Db::rollBack(); + return '优惠券使用失败'; + } + + } + } + + Db::commit(); + + + } catch (Exception $e) { + + Db::rollBack(); + return $e->getMessage(); + + } + + // 订单成功后处理 + if ($orderMainId) { + + // 处理喇叭播报 + + + } + + return $orderMainId; + } + + /** + * @inheritDoc + */ + public function addOfflineOrder() + { + // TODO: Implement addOfflineOrder() method. + } + + + + /** + * 计算和校验当前订单可用红包及金额 + * @param $couponIds + * @param $orderAmount + * @param $userId + * @param $marketId + * @throws Exception + */ + protected function getCouponAmount($couponIds, $orderAmount, $userId, $marketId) + { + + // 用户当前订单可用优惠券 + $couponsCanUse = $this->couponService->getOrderCanUseCoupons( + $orderAmount, + $marketId, + $userId, + [ + 'receive.id', + 'receive.user_id', + 'receive.number', + 'receive.number_remain', + 'receive.system_coupon_user_id', + 'coupon.discounts', + 'coupon.discount_type', + ] + ); + + $couponCanUseIds = array_column($couponsCanUse, 'id'); + $couponCanUseIds = array_intersect($couponCanUseIds, $couponIds); + $couponCannotUseIds = array_diff($couponIds, $couponCanUseIds); + + if (empty($couponCanUseIds)||!empty($couponCannotUseIds)) { + throw new Exception('您的订单中有优惠券已经失效'); + } + + // 计算红包折扣金额 + $couponMoney = 0; + foreach ($couponsCanUse as $key => $coupon) { + + if (!in_array($coupon->id, $couponIds)) { + continue; + } + + if ($coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) { + $couponMoney = bcadd($couponMoney, $coupon->discounts, 2); + } elseif ($coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) { + $discountRate = bcdiv($coupon->discounts,10); + $discountRate = bcsub(1,$discountRate); + $discountMoney = bcmul($orderAmount, $discountRate); + $couponMoney = bcadd($couponMoney, $discountMoney, 2); + } + } + + return $couponMoney; + + } + + /** + * 订单是否存在 + * @param $orderNum + * @return \Hyperf\Utils\HigherOrderTapProxy|mixed|void|null + */ + public function existsByOrderNum($orderNum) + { + return OrderMain::query()->where(['order_num' => $orderNum])->value('id'); + } +} \ No newline at end of file diff --git a/app/Service/OrderServiceInterface.php b/app/Service/OrderServiceInterface.php new file mode 100644 index 0000000..08ee815 --- /dev/null +++ b/app/Service/OrderServiceInterface.php @@ -0,0 +1,29 @@ +mqttClient = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT')); + $this->mqttClient->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS')); + + if (env('MQTT_CERT')) { + $this->mqttClient->setEncryption(env('MQTT_CERT')); + } + + return $this->mqttClient; + } +} \ No newline at end of file diff --git a/composer.json b/composer.json index 1ac7889..d8f86c6 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,10 @@ "hyperf/constants": "~2.0.0", "hyperf/model-cache": "~2.0.0", "hyperf/validation": "^2.0", - "hyperf/paginator": "^2.0" + "hyperf/paginator": "^2.0", + "hyperf/snowflake": "^2.0", + "ext-bcmath": "*", + "hyperf/task": "^2.0" }, "require-dev": { "swoole/ide-helper": "^4.5", diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index cccee93..a4028ee 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -10,5 +10,7 @@ declare(strict_types=1); * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ return [ - \App\Service\ServiceEvaluateServiceInterface::class => \App\Service\ServiceEvaluateService::class + \App\Service\ServiceEvaluateServiceInterface::class => \App\Service\ServiceEvaluateService::class, + \App\Service\OrderServiceInterface::class => \App\Service\OrderService::class, + \App\Service\CoupnoServiceInterface::class => \App\Service\CouponService::class, ]; diff --git a/config/autoload/server.php b/config/autoload/server.php index e0e6cd8..f44b083 100644 --- a/config/autoload/server.php +++ b/config/autoload/server.php @@ -36,16 +36,13 @@ return [ 'max_request' => 100000, 'socket_buffer_size' => 2 * 1024 * 1024, 'buffer_output_size' => 2 * 1024 * 1024, - // Task Worker 数量,根据您的服务器配置而配置适当的数量 'task_worker_num' => 8, - // 因为 `Task` 主要处理无法协程化的方法,所以这里推荐设为 `false`,避免协程下出现数据混淆的情况 'task_enable_coroutine' => false, ], 'callbacks' => [ SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'], SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'], SwooleEvent::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'], - // Task callbacks SwooleEvent::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'], SwooleEvent::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'], ], diff --git a/config/autoload/snowflake.php b/config/autoload/snowflake.php new file mode 100644 index 0000000..279de42 --- /dev/null +++ b/config/autoload/snowflake.php @@ -0,0 +1,24 @@ + MetaGeneratorInterface::DEFAULT_BEGIN_SECOND, + RedisMilliSecondMetaGenerator::class => [ + 'pool' => 'default', + ], + RedisSecondMetaGenerator::class => [ + 'pool' => 'default', + ], +]; diff --git a/config/routes.php b/config/routes.php index 706a9ab..c14f389 100644 --- a/config/routes.php +++ b/config/routes.php @@ -23,4 +23,5 @@ Router::addGroup('/v1/',function (){ Router::post('ServiceEvaluate/isPersonnel', 'App\Controller\ServiceEvaluateController@isPersonnel'); Router::post('ServiceEvaluate/getPersonnelInfo', 'App\Controller\ServiceEvaluateController@getPersonnelInfo'); Router::post('ServiceEvaluate/getEvaluateList', 'App\Controller\ServiceEvaluateController@getEvaluateList'); + Router::post('Order/addOnline', 'App\Controller\OrderController@addOnlineOrder'); }); \ No newline at end of file From d13bd3253888e62feae0f2bd73e96d2fd4480b88 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Wed, 12 Aug 2020 12:04:32 +0800 Subject: [PATCH 099/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E5=8F=AA=E6=9C=89=E5=8A=A0?= =?UTF-8?q?=E8=BF=9B=E6=B4=BB=E5=8A=A8=E7=9A=84=E5=88=B8=E6=89=8D=E8=BF=94?= =?UTF-8?q?=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponService.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index b0aa716..994b899 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -70,8 +70,8 @@ class CouponService implements CouponServiceInterface // 当前用户可领的优惠券ID $couponIds = array_diff($c_ids, $cr_ids); - // 获取领取型优惠券 - $couponIds = $couponActivity['forward'] === false ? $couponIds : array_merge($couponIds,explode(',',$couponActivity['forward'])); + // 转发型优惠券 + $couponReceiveIds = $couponActivity === false ? [] : explode(',',$couponActivity['forward']); $whereC = [ ['u.end_time','>',$nowTime], @@ -97,7 +97,7 @@ class CouponService implements CouponServiceInterface if($v->active_type == 1){ $result['not_receive'][] = $v; - }else if($v->active_type == 2){ + }else if($v->active_type == 2 && in_array($v->id,$couponReceiveIds)){ $result['jump_data']['coupons'][] = $v->id; } From 054b2a8ea4739494c31e68f3941e9e2fc8887e2d Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Wed, 12 Aug 2020 14:33:22 +0800 Subject: [PATCH 100/172] =?UTF-8?q?=E8=BF=94=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 49c085c..7a2f310 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -290,6 +290,11 @@ class CouponRebateService implements CouponRebateServiceInterface //开启事务 Db::beginTransaction(); try { + //读写锁 + Db::table('ims_system_user') + ->lockForUpdate() + ->where('id', $active['repay']) + ->get(); //返券 if($exists_coupon_rebate){ //如果已有该优惠券 则领取数量 和 可用数量 自增1 From 0a6fdc159f583c7df7aa219ae8b4ac8a7db98671 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Wed, 12 Aug 2020 14:35:25 +0800 Subject: [PATCH 101/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E6=B8=85?= =?UTF-8?q?=E9=99=A4=E9=A2=86=E5=8F=96=E7=BC=93=E5=AD=98=EF=BC=88ssdb?= =?UTF-8?q?=EF=BC=89=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 539a404..56e9da7 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -397,8 +397,6 @@ class CouponRebateService implements CouponRebateServiceInterface return ( $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE) === false) ? false : true ; } }else { - $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ); - if($get > 0){ return $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key); }else{ From e99bcfdbf051b350f385ebbd2645d260116f0e7c Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 14:35:51 +0800 Subject: [PATCH 102/172] =?UTF-8?q?=E5=A4=96=E5=8D=96=E4=B8=8B=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 4 +- app/Controller/OrderController.php | 12 +++++- app/Model/OrderMain.php | 36 +++++++++-------- app/Service/CouponService.php | 14 +------ app/Service/OrderService.php | 50 ++++++++++++------------ 5 files changed, 61 insertions(+), 55 deletions(-) diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index d0aa997..f6e58bc 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -65,7 +65,9 @@ class DevicOrderConsumer extends ConsumerMessage public function isEnable(): bool { - // if(env('APP_ENV')!='prod') return false; + if(env('APP_ENV') == 'local') { + return false; + } return parent::isEnable(); } } diff --git a/app/Controller/OrderController.php b/app/Controller/OrderController.php index 0973da0..8757ff9 100644 --- a/app/Controller/OrderController.php +++ b/app/Controller/OrderController.php @@ -5,6 +5,7 @@ namespace App\Controller; use App\Request\OrderOnlineRequest; use Hyperf\Di\Annotation\Inject; use App\Service\OrderServiceInterface; +use Hyperf\HttpMessage\Stream\SwooleStream; class OrderController extends BaseController { @@ -18,6 +19,15 @@ class OrderController extends BaseController public function addOnlineOrder(OrderOnlineRequest $request) { $orderMainId = $this->orderService->addOnlineOrder($request->validated()); - return $this->success(['order_main_id' => $orderMainId]); + if (!is_int($orderMainId)) { + return $this->response + ->withHeader('Content-Type', 'application/text') + ->withStatus(500) + ->withBody(new SwooleStream($orderMainId)); + } + return $this->response + ->withHeader('Content-Type', 'application/text') + ->withStatus(200) + ->withBody(new SwooleStream($orderMainId)); } } \ No newline at end of file diff --git a/app/Model/OrderMain.php b/app/Model/OrderMain.php index 1a0a7e9..ee3840c 100644 --- a/app/Model/OrderMain.php +++ b/app/Model/OrderMain.php @@ -6,41 +6,43 @@ namespace App\Model; class OrderMain extends Model { - // ϶ + // 线上订单,外卖 const ORDER_TYPE_ONLINE = 1; - // ¶渶 + // 线下订单,当面付 const ORDER_TYPE_OFFLINE = 4; - // ״̬ - // + // 订单状态 + // 待付款 const ORDER_STATE_UNPAY = 1; - // ӵ + // 待接单 const ORDER_STATE_UNTAKE = 2; - // ʹ + // 待送达 const ORDER_STATE_DELIVERY = 3; - // + // 已完成 const ORDER_STATE_COMPLETE = 4; - // + // 已评价 const ORDER_STATE_EVALUATED = 5; - // ȡ + // 已取消 const ORDER_STATE_CANCEL = 6; - // Ѿܵ + // 已拒单 const ORDER_STATE_REFUSE = 7; - // ˿ + // 退款中 const ORDER_STATE_REFUNDING = 8; - // ˿ + // 已退款 const ORDER_STATE_REFUNDED = 9; - // ܾ˿ + // 拒绝退款 const ORDER_STATE_UNREFUND = 10; - // ֧ʽ - // ΢֧ + // 订单支付方式 + // 微信支付 const ORDER_PAY_WX = 1; - // ֧ + // 余额支付 const ORDER_PAY_BALANCE = 2; protected $table = 'ims_cjdc_order_main'; + public $timestamps = false; + protected $fillable = [ 'order_num', 'delivery_no', @@ -75,6 +77,8 @@ class OrderMain extends Model 'state', 'time', 'time_add', + 'pay_time', + 'jj_note', 'global_order_id', ]; diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index f1d4bf5..f4f8af9 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -18,25 +18,13 @@ class CouponService implements CoupnoServiceInterface // 用户今日使用过的优惠券 $redis = ApplicationContext::getContainer()->get(Redis::class); $couponTodayUsedIds = $redis->sMembers('coupon_'.date('Ymd').'_used_'.$userId); - $currentTime = time(); $builder = Db::table('ims_system_coupon_user_receive as receive') ->join('ims_system_coupon_user as coupon', 'coupon.id', '=', 'receive.system_coupon_user_id', 'inner'); if (is_array($fields)&&!empty($fields)) { - $builder->select([ - 'receive.id as receive_id', - 'receive.user_id', - 'receive.number_remain', - 'coupon.id', - 'coupon.title', - 'coupon.full_amount', - 'coupon.discounts', - 'coupon.usable_start_time', - 'coupon.usable_end_time', - 'coupon.discount_type' - ]); + $builder->select($fields); } if (is_array($couponTodayUsedIds)&&!empty($couponTodayUsedIds)) { diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index e16d2cb..25a44e5 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -57,7 +57,7 @@ class OrderService implements OrderServiceInterface // 店铺IDs $dataMain['store_ids'] = ''; - $storeList = json_decode(json_encode($data['store_list']), true); + $storeList = json_decode(html_entity_decode($data['store_list']), true); if (!is_array($storeList)||empty($storeList)) { Db::rollBack(); return '订单中商品不存在或已失效'; @@ -72,15 +72,19 @@ class OrderService implements OrderServiceInterface $currentTime = time(); $dataMain['time'] = date('Y-m-d H:i:s', $currentTime); $dataMain['time_add'] = $currentTime; + $dataMain['pay_time'] = date('Y-m-d H:i:s', $currentTime); $dataMain['state'] = OrderMain::ORDER_STATE_UNPAY; $dataMain['code'] = $dataMain['global_order_id']; + $dataMain['jj_note'] = ''; // 主订单模型保存 $orderMain = OrderMain::create($dataMain); $orderMainId = $orderMain->id; // 统计订单中所有店铺当日订单数,做店铺订单序号 - $countsArr = Order::query()->select('COUNT(*) AS count, id') + $countsArr = Order::query() + ->selectRaw('COUNT(*) AS count') + ->select('id') ->whereIn('store_id', explode(',', $dataMain['store_ids'])) ->where(['type' => OrderMain::ORDER_TYPE_ONLINE]) ->whereBetween('time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')]) @@ -102,14 +106,14 @@ class OrderService implements OrderServiceInterface 'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999), 'user_id' => $orderMain->user_id, 'store_id' => $item['store_id'], - 'order_main_id' => $orderMain, + 'order_main_id' => $orderMainId, 'state' => OrderMain::ORDER_STATE_UNPAY, 'tel' => $orderMain->tel, 'name' => $orderMain->name, 'address' => $orderMain->address, 'area' => $orderMain->area, 'time' => date("Y-m-d H:i:s"), - 'note' => $item['note'], + 'note' => $item['note'] ?? '', 'delivery_time' => $orderMain->delivery_time, 'type' => $orderMain->type, 'lat' => $orderMain->lat, @@ -127,10 +131,13 @@ class OrderService implements OrderServiceInterface 'xyh_money' => floatval($item['xyh_money']), 'oid' => (isset($storeOrderCounts[$item['store_id']]) ? $item['store_id'] : 0) + 1, 'time_add' => date("Y-m-d H:i:s"), + 'jj_note' => '', + 'form_id' => '', + 'form_id2' => '', + 'code' => '', ]; - $order = Order::create($dataChild); - $orderChildId = $order->id; + $orderChildId = Order::query()->insertGetId($dataChild); // 子订单内商品处理 $goodsAmountTotal = 0; @@ -140,7 +147,6 @@ class OrderService implements OrderServiceInterface return '订单商品异常'; } foreach ($item['good_list'] as &$goods) { - $goodsAmount = bcadd(floatval($goods['money']), floatval($goods['box_money'])); $goodsAmount = bcmul($goodsAmount, $goods['num']); $goodsAmountTotal = bcadd($goodsAmountTotal, $goodsAmount); @@ -170,7 +176,7 @@ class OrderService implements OrderServiceInterface } // 校验库存 - foreach ($orderGoods as $Key=>&$goodsItem) { + foreach ($orderGoods as $Key => &$goodsItem) { $goodsItem['combination_id'] = intval($goodsItem['combination_id']); @@ -179,21 +185,27 @@ class OrderService implements OrderServiceInterface if ($goodsItem['combination_id'] > 0) { $goods = SpecCombination::query() - ->select('id, number AS inventory') + ->with(['goods' => function($query){ + $query->select(['name', 'is_max']); + }]) + ->select(['id', 'number AS inventory']) ->where(['id' => $goodsItem['combination_id']]) - ->first(); + ->first() + ->toArray(); $goods->name = $goods->goods->name; $goods->is_max = $goods->goods->is_max; } else { $goods = Goods::query() - ->select('id, name, is_max, inventory') + ->select(['id', 'name', 'is_max', 'inventory']) ->where(['id' => $goodsItem['good_id']]) - ->first(); + ->first() + ->toArray(); } + var_dump('$goods', $goods); if (!$goods) { Db::rollBack(); return '缺少商品'; @@ -243,7 +255,7 @@ class OrderService implements OrderServiceInterface $goods['combination_id'] = $value['combination_id']; $orderGoods[] = $goods; } - + var_dump('$orderGoods', $orderGoods); $addOrderGoods = OrderGoods::query()->insert($orderGoods); if (!$addOrderGoods) { Db::rollBack(); @@ -324,7 +336,7 @@ class OrderService implements OrderServiceInterface } Db::commit(); - + return $orderMainId; } catch (Exception $e) { @@ -332,16 +344,6 @@ class OrderService implements OrderServiceInterface return $e->getMessage(); } - - // 订单成功后处理 - if ($orderMainId) { - - // 处理喇叭播报 - - - } - - return $orderMainId; } /** From 2a7acba6d53e7ab13fdc492d6a5d729c10686e1f Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Wed, 12 Aug 2020 14:42:48 +0800 Subject: [PATCH 103/172] =?UTF-8?q?=E8=BF=94=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponRebateService.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php index 7a2f310..49c085c 100644 --- a/app/Service/CouponRebateService.php +++ b/app/Service/CouponRebateService.php @@ -290,11 +290,6 @@ class CouponRebateService implements CouponRebateServiceInterface //开启事务 Db::beginTransaction(); try { - //读写锁 - Db::table('ims_system_user') - ->lockForUpdate() - ->where('id', $active['repay']) - ->get(); //返券 if($exists_coupon_rebate){ //如果已有该优惠券 则领取数量 和 可用数量 自增1 From 88ae5b544be899640afd4ac40faa29935fb5d9e0 Mon Sep 17 00:00:00 2001 From: Mike Date: Wed, 12 Aug 2020 14:52:32 +0800 Subject: [PATCH 104/172] =?UTF-8?q?=E5=B0=81=E8=A3=85w7=E6=97=A7=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E6=95=B0=E6=8D=AE=E8=BF=94=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/BaseController.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/app/Controller/BaseController.php b/app/Controller/BaseController.php index 40d2813..ffa8c77 100644 --- a/app/Controller/BaseController.php +++ b/app/Controller/BaseController.php @@ -13,9 +13,18 @@ namespace App\Controller; use Hyperf\HttpServer\Contract\ResponseInterface; use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface; +use Hyperf\HttpMessage\Stream\SwooleStream; class BaseController extends AbstractController { + + public function w7result($statusCode,$data = ''){ + return $this->response + ->withHeader('Content-Type', 'application/text') + ->withStatus($statusCode) + ->withBody(new SwooleStream($data)); + } + public function result($code, $data, $message = '成功'):Psr7ResponseInterface { $status = 'ok'; From 510023ded067f5b3f748a840ef7303e310ca4f18 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Wed, 12 Aug 2020 14:58:17 +0800 Subject: [PATCH 105/172] =?UTF-8?q?=E9=98=9F=E5=88=97=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index 9a0a414..a76f046 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -16,7 +16,7 @@ use Hyperf\Di\Annotation\Inject; /** - * @Consumer(exchange="deviceCouponRebate1", routingKey="deviceCouponRebate1", queue="deviceCouponRebate1", name ="couponRebateConsumer", nums=1) + * @Consumer(exchange="deviceCouponRebate", routingKey="deviceCouponRebate", queue="deviceCouponRebate", name ="couponRebateConsumer", nums=1) */ class couponRebateConsumer extends ConsumerMessage { From 5729da8d1c04ad28a31f018ac9deaa7fe1a1b237 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 15:18:39 +0800 Subject: [PATCH 106/172] =?UTF-8?q?=E5=A4=96=E5=8D=96=E4=B8=8B=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/OrderController.php | 10 +---- app/Service/OrderService.php | 67 +++++++++++++++--------------- 2 files changed, 36 insertions(+), 41 deletions(-) diff --git a/app/Controller/OrderController.php b/app/Controller/OrderController.php index 8757ff9..8d93c54 100644 --- a/app/Controller/OrderController.php +++ b/app/Controller/OrderController.php @@ -20,14 +20,8 @@ class OrderController extends BaseController { $orderMainId = $this->orderService->addOnlineOrder($request->validated()); if (!is_int($orderMainId)) { - return $this->response - ->withHeader('Content-Type', 'application/text') - ->withStatus(500) - ->withBody(new SwooleStream($orderMainId)); + return $this->w7result(500, $orderMainId); } - return $this->response - ->withHeader('Content-Type', 'application/text') - ->withStatus(200) - ->withBody(new SwooleStream($orderMainId)); + return $this->w7result(200, $orderMainId); } } \ No newline at end of file diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 25a44e5..374631e 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -180,20 +180,22 @@ class OrderService implements OrderServiceInterface $goodsItem['combination_id'] = intval($goodsItem['combination_id']); - // 存在规格,则去规格处查库存,整个接口还有很多别的问题,目前 - $goods = (object)[]; + // 存在规格,则去规格处查库存 + $goods = []; if ($goodsItem['combination_id'] > 0) { - $goods = SpecCombination::query() - ->with(['goods' => function($query){ - $query->select(['name', 'is_max']); - }]) - ->select(['id', 'number AS inventory']) + $combination = SpecCombination::query() + ->select(['good_id AS id', 'number AS inventory']) ->where(['id' => $goodsItem['combination_id']]) ->first() ->toArray(); - $goods->name = $goods->goods->name; - $goods->is_max = $goods->goods->is_max; + + $goods = Goods::query() + ->select(['id', 'name', 'is_max']) + ->where(['id' => $combination['id']]) + ->first() + ->toArray(); + $goods['inventory'] = $combination['inventory']; } else { @@ -205,13 +207,12 @@ class OrderService implements OrderServiceInterface } - var_dump('$goods', $goods); if (!$goods) { Db::rollBack(); return '缺少商品'; } - if($goodsItem['num'] > $goods->inventory && $goods->is_max != Goods::INVENTORY_NOLIMIT){ + if($goodsItem['num'] > $goods['inventory'] && $goods['is_max'] != Goods::INVENTORY_NOLIMIT){ Db::rollBack(); return '商品 '.$goods->name.' 库存不足!'; } @@ -241,21 +242,21 @@ class OrderService implements OrderServiceInterface $tempGoods = $orderGoods; $orderGoods = []; foreach ($tempGoods as $key => &$value) { - $goods['good_id'] = $value['good_id']; - $goods['img'] = $value['logo']; - $goods['number'] = $value['num']; - $goods['order_id'] = $value['order_id']; - $goods['name'] = $value['name']; - $goods['money'] = $value['money']; - $goods['dishes_id'] = $value['dishes_id']; - $goods['spec'] = $value['spec']; - $goods['is_qg'] = $value['is_qg']; - $goods['good_unit'] = $value['good_unit']; - $goods['uniacid'] = $value['uniacid']; - $goods['combination_id'] = $value['combination_id']; - $orderGoods[] = $goods; + $goodsTemp['good_id'] = $value['good_id']; + $goodsTemp['img'] = $value['logo']; + $goodsTemp['number'] = $value['num']; + $goodsTemp['order_id'] = $value['order_id']; + $goodsTemp['name'] = $value['name']; + $goodsTemp['money'] = $value['money']; + $goodsTemp['dishes_id'] = $value['dishes_id']; + $goodsTemp['spec'] = $value['spec']; + $goodsTemp['is_qg'] = $value['is_qg']; + $goodsTemp['good_unit'] = $value['good_unit']; + $goodsTemp['uniacid'] = $value['uniacid']; + $goodsTemp['combination_id'] = $value['combination_id']; + $orderGoods[] = $goodsTemp; } - var_dump('$orderGoods', $orderGoods); + $addOrderGoods = OrderGoods::query()->insert($orderGoods); if (!$addOrderGoods) { Db::rollBack(); @@ -290,9 +291,9 @@ class OrderService implements OrderServiceInterface # 使用记录、更新当前优惠券 foreach ($canUseConpons as $key => &$coupon) { $couponUse = [ - 'user_id' => $coupon['user_id'], - 'user_receive_id' => $coupon['id'], - 'system_coupon_id' => $coupon['system_coupon_user_id'], + 'user_id' => $coupon->user_id, + 'user_receive_id' => $coupon->id, + 'system_coupon_id' => $coupon->system_coupon_user_id, 'order_main_id' => $orderMainId, 'use_time' => $currentTime, 'return_time' => 0, @@ -304,16 +305,16 @@ class OrderService implements OrderServiceInterface $insertRes = CouponUserUse::query()->insert($couponUse); if ($insertRes) { - $numberRemain = $coupon['number_remain'] - 1; + $numberRemain = $coupon->number_remain - 1; if ($numberRemain == 0) { $status = 2; - } elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) { + } elseif ($numberRemain > 0 && $numberRemain < $coupon->number) { $status = 1; - } elseif ($numberRemain == $coupon['number']) { + } elseif ($numberRemain == $coupon->number) { $status = 0; } - $upRes = CouponUserRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]); + $upRes = CouponUserRec::query()->where(['id' => $coupon->id])->update(['number_remain' => $numberRemain, 'status' => $status]); if (!$upRes) { Db::rollBack(); @@ -321,7 +322,7 @@ class OrderService implements OrderServiceInterface } // 缓存使用记录 - $usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']); + $usedRes = $this->couponService->cacheTodayCouponUsed($coupon->user_id, $coupon->system_coupon_user_id, $coupon->id); if (!$usedRes) { Db::rollBack(); return '优惠券使用失败'; From 3828ac8225e24eea84131479d6a3224751d9a7d1 Mon Sep 17 00:00:00 2001 From: Mike Date: Wed, 12 Aug 2020 15:35:19 +0800 Subject: [PATCH 107/172] =?UTF-8?q?=E5=BE=AE=E4=BF=A1=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 4 ++ app/Request/BaseFormRequest.php | 26 +++++++++++++ app/Request/WxminiPayRequest.php | 58 ++++++++++++++++++++++++++++ config/routes.php | 4 ++ 4 files changed, 92 insertions(+) create mode 100644 app/Request/BaseFormRequest.php create mode 100644 app/Request/WxminiPayRequest.php diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index 86ce06c..14fbc48 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -7,4 +7,8 @@ namespace App\Controller; class PaymentController extends BaseController { + public function wxminiPay(){ + + } + } \ No newline at end of file diff --git a/app/Request/BaseFormRequest.php b/app/Request/BaseFormRequest.php new file mode 100644 index 0000000..14bbc31 --- /dev/null +++ b/app/Request/BaseFormRequest.php @@ -0,0 +1,26 @@ +withStatus(200); + // } +} \ No newline at end of file diff --git a/app/Request/WxminiPayRequest.php b/app/Request/WxminiPayRequest.php new file mode 100644 index 0000000..0a7f6dd --- /dev/null +++ b/app/Request/WxminiPayRequest.php @@ -0,0 +1,58 @@ + 'required|nonempty|integer', + 'c_service' => 'required|nonempty|integer', + 'c_quality' => 'required|nonempty|integer', + 'content' => 'required|nonempty|strlen:15,150', + 'user_id' => 'required|nonempty|integer|exists:ims_cjdc_user,id', + 'service_personnel_id' => 'required|nonempty|integer|exists_enable:lanzu_service_personnel,id,status=1|not_equal:user_id,lanzu_service_personnel,id,user_id', + 'market_id' => 'required|nonempty|integer|exists:ims_cjdc_market,id', + ]; + } + + public function messages(): array + { + return [ + 'user_id.exists' => ':attribute不存在', + 'service_personnel_id.exists' => ':attribute不存在', + 'market_id.exists' => ':attribute不存在', + 'user_id.*' => ':attribute信息不正确', + 'service_personnel_id.exists_enable' => ':attribute不存在或被禁用', + 'service_personnel_id.not_equal' => ':attribute不能是自己', + 'service_personnel_id.*' => ':attribute信息不正确', + 'market_id.*' => ':attribute信息不正确', + 'c_attitude.*' => ':attribute信息不正确', + 'c_service.*' => ':attribute信息不正确', + 'c_quality.*' => ':attribute信息不正确', + 'content.strlen' => ':attribute字数限制在:min~:max字', + 'content.*' => ':attribute信息不正确', + ]; + } + + public function attributes(): array + { + return [ + 'user_id' => '用户', + 'service_personnel_id' => '服务专员', + 'market_id' => '服务专员市场', + 'c_attitude' => '服务态度评分', + 'c_service' => '服务值评分', + 'c_quality' => '服务质量评分', + 'content' => '服务评价内容', + ]; + } +} \ No newline at end of file diff --git a/config/routes.php b/config/routes.php index 3979aa7..dfdf5ab 100644 --- a/config/routes.php +++ b/config/routes.php @@ -39,4 +39,8 @@ Router::addGroup('/v1/',function (){ //订单相关 Router::post('Order/addOnline', 'App\Controller\OrderController@addOnlineOrder'); + + //小程序支付相关 + Router::post('wxmini/pay', 'App\Controller\PaymentController@wxminiPay'); + }); \ No newline at end of file From 4baa6f8706bc99614020fd5ac9a731997f69b194 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Wed, 12 Aug 2020 16:59:44 +0800 Subject: [PATCH 108/172] =?UTF-8?q?=E5=8F=AF=E9=A2=86=E5=8F=96=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3bug=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponService.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 994b899..6105ea5 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -72,7 +72,7 @@ class CouponService implements CouponServiceInterface // 转发型优惠券 $couponReceiveIds = $couponActivity === false ? [] : explode(',',$couponActivity['forward']); - + $whereC = [ ['u.end_time','>',$nowTime], ['u.start_time','<=',$nowTime], @@ -85,7 +85,7 @@ class CouponService implements CouponServiceInterface $coupons = Db::table('ims_system_coupon_user as u') ->join('ims_system_coupon_user_receivetype as type', 'u.id', '=', 'type.system_coupon_user_id') - ->whereIn('u.id', $couponIds) + ->whereIn('u.id', $couponReceiveIds) ->where($whereC) ->whereRaw('u.inventory_use < u.inventory and u.inventory-u.inventory_use >= type.one_receive_number') ->select('u.*','type.one_receive_number') From b6e4ae364e5844c6d6f3c0bb2e990846ac355f87 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 17:16:02 +0800 Subject: [PATCH 109/172] =?UTF-8?q?=E4=B8=8B=E5=8D=95=E6=94=AF=E4=BB=98JSA?= =?UTF-8?q?PI=EF=BC=8CTODO=20=E6=94=AF=E4=BB=98=E6=88=90=E5=8A=9F=E9=80=9A?= =?UTF-8?q?=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/LogLabel.php | 5 +++ app/Controller/NotifyController.php | 10 ++++- app/Controller/OrderController.php | 4 +- app/Controller/PaymentController.php | 37 +++++++++++++++++-- .../Handler/ValidationExceptionHandler.php | 2 +- app/Request/OrderOnlineRequest.php | 4 +- app/Request/WxminiPayRequest.php | 34 ++++------------- app/Service/OrderService.php | 2 +- composer.json | 3 +- config/config.php | 11 +++++- config/routes.php | 1 + 11 files changed, 71 insertions(+), 42 deletions(-) diff --git a/app/Constants/LogLabel.php b/app/Constants/LogLabel.php index b3cadb4..aafacd8 100644 --- a/app/Constants/LogLabel.php +++ b/app/Constants/LogLabel.php @@ -21,4 +21,9 @@ class LogLabel extends AbstractConstants * @Message("Device Speaker Log Label") */ const DEVICE_LOG = 'device_log'; + + /** + * @Message("Pay Notice Log Label") + */ + const PAY_NOTIFY_WXMINI = 'notify_wxmini'; } diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 8aa0ba0..02aa0a3 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -1,10 +1,16 @@ log->event( + LogLabel::PAY_NOTIFY_WXMINI, + json_encode($this->request->input()) + ); + } } \ No newline at end of file diff --git a/app/Controller/OrderController.php b/app/Controller/OrderController.php index 8d93c54..89a1cad 100644 --- a/app/Controller/OrderController.php +++ b/app/Controller/OrderController.php @@ -20,8 +20,8 @@ class OrderController extends BaseController { $orderMainId = $this->orderService->addOnlineOrder($request->validated()); if (!is_int($orderMainId)) { - return $this->w7result(500, $orderMainId); + return $this->w7result(500, (string)$orderMainId); } - return $this->w7result(200, $orderMainId); + return $this->w7result(200, (string)$orderMainId); } } \ No newline at end of file diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index 14fbc48..29b88e3 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -1,14 +1,45 @@ validated(); + + $config = config('wxpay'); + $app = Factory::payment($config); + $app['guzzle_handler'] = CoroutineHandler::class; + + // 待支付的,类型一致的,未超时(15min,900sec)的订单 + $orderMain = OrderMain::query() + ->where(['state' => OrderMain::ORDER_STATE_UNPAY, 'type' => $data['type'], 'id' => $data['order_id']]) + ->where('time', '<=', date('Y-m-d H:i:s', (time()-900))) + ->first(); + + if (empty($orderMain)) { + return $this->result(200, ['order_id' => $data['order_id']],'订单不存在或已失效'); + } + + $result = $app->order->unify([ + 'body' => '懒族生活 - 外卖下单', + 'out_trade_no' => $orderMain->global_order_id, + 'total_fee' => bcmul(floatval($orderMain->money), 100), + 'notify_url' => config('site_host') . '/v1/notify/wxmini', + 'trade_type' => 'JSAPI', + 'openid' => $data['openid'], + ]); + + return $this->success($result); } } \ No newline at end of file diff --git a/app/Exception/Handler/ValidationExceptionHandler.php b/app/Exception/Handler/ValidationExceptionHandler.php index cc2384c..cee5579 100644 --- a/app/Exception/Handler/ValidationExceptionHandler.php +++ b/app/Exception/Handler/ValidationExceptionHandler.php @@ -24,7 +24,7 @@ class ValidationExceptionHandler extends ExceptionHandler ]); return $response->withHeader('Content-Type', 'application/json') - ->withStatus($throwable->status) + ->withStatus(200) ->withBody(new SwooleStream($content)); } diff --git a/app/Request/OrderOnlineRequest.php b/app/Request/OrderOnlineRequest.php index dfe0ae6..019cc99 100644 --- a/app/Request/OrderOnlineRequest.php +++ b/app/Request/OrderOnlineRequest.php @@ -4,9 +4,7 @@ declare(strict_types=1); namespace App\Request; -use Hyperf\Validation\Request\FormRequest; - -class OrderOnlineRequest extends FormRequest +class OrderOnlineRequest extends BaseFormRequest { /** * Determine if the user is authorized to make this request. diff --git a/app/Request/WxminiPayRequest.php b/app/Request/WxminiPayRequest.php index 0a7f6dd..2307691 100644 --- a/app/Request/WxminiPayRequest.php +++ b/app/Request/WxminiPayRequest.php @@ -14,45 +14,25 @@ class WxminiPayRequest extends BaseFormRequest public function rules(): array { return [ - 'c_attitude' => 'required|nonempty|integer', - 'c_service' => 'required|nonempty|integer', - 'c_quality' => 'required|nonempty|integer', - 'content' => 'required|nonempty|strlen:15,150', - 'user_id' => 'required|nonempty|integer|exists:ims_cjdc_user,id', - 'service_personnel_id' => 'required|nonempty|integer|exists_enable:lanzu_service_personnel,id,status=1|not_equal:user_id,lanzu_service_personnel,id,user_id', - 'market_id' => 'required|nonempty|integer|exists:ims_cjdc_market,id', + 'order_id' => 'required|nonempty|integer', + 'type' => 'required|nonempty|integer', + 'openid' => 'required|nonempty', ]; } public function messages(): array { return [ - 'user_id.exists' => ':attribute不存在', - 'service_personnel_id.exists' => ':attribute不存在', - 'market_id.exists' => ':attribute不存在', - 'user_id.*' => ':attribute信息不正确', - 'service_personnel_id.exists_enable' => ':attribute不存在或被禁用', - 'service_personnel_id.not_equal' => ':attribute不能是自己', - 'service_personnel_id.*' => ':attribute信息不正确', - 'market_id.*' => ':attribute信息不正确', - 'c_attitude.*' => ':attribute信息不正确', - 'c_service.*' => ':attribute信息不正确', - 'c_quality.*' => ':attribute信息不正确', - 'content.strlen' => ':attribute字数限制在:min~:max字', - 'content.*' => ':attribute信息不正确', + '*.*' => ':attribute 参数异常', ]; } public function attributes(): array { return [ - 'user_id' => '用户', - 'service_personnel_id' => '服务专员', - 'market_id' => '服务专员市场', - 'c_attitude' => '服务态度评分', - 'c_service' => '服务值评分', - 'c_quality' => '服务质量评分', - 'content' => '服务评价内容', + 'order_id' => '订单', + 'type' => '订单类型', + 'openid' => '用户标识', ]; } } \ No newline at end of file diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 374631e..321c1f7 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -72,7 +72,7 @@ class OrderService implements OrderServiceInterface $currentTime = time(); $dataMain['time'] = date('Y-m-d H:i:s', $currentTime); $dataMain['time_add'] = $currentTime; - $dataMain['pay_time'] = date('Y-m-d H:i:s', $currentTime); + $dataMain['pay_time'] = ''; $dataMain['state'] = OrderMain::ORDER_STATE_UNPAY; $dataMain['code'] = $dataMain['global_order_id']; $dataMain['jj_note'] = ''; diff --git a/composer.json b/composer.json index dfc0c2b..0e16cf6 100644 --- a/composer.json +++ b/composer.json @@ -35,7 +35,8 @@ "alibabacloud/iot": "^1.8", "hyperf/amqp": "^2.0", "hyperf/snowflake": "^2.0", - "ext-bcmath": "*" + "ext-bcmath": "*", + "overtrue/wechat": "~4.0" }, "require-dev": { "swoole/ide-helper": "^4.5", diff --git a/config/config.php b/config/config.php index c5ce284..c67f910 100644 --- a/config/config.php +++ b/config/config.php @@ -28,7 +28,14 @@ return [ LogLevel::WARNING, ], ], - - 'site_host'=>'http://store.api.lanzulive.com/' + 'site_host'=> env('SITE_HOST', ''), + 'wxpay' => [ + 'app_id' => env('APP_ID',''), + 'mch_id' => env('MCH_ID',''), + 'key' => env('APP_SECRET',''), + 'cert_path' => env('CERT_PATH',''), + 'key_path' => env('KEY_PATH',''), + 'notify_url' => env('NOTIFY_URL',''), + ] ]; diff --git a/config/routes.php b/config/routes.php index dfdf5ab..2393433 100644 --- a/config/routes.php +++ b/config/routes.php @@ -42,5 +42,6 @@ Router::addGroup('/v1/',function (){ //小程序支付相关 Router::post('wxmini/pay', 'App\Controller\PaymentController@wxminiPay'); + Router::post('notify/wxmini', 'App\Controller\NotifyController@wxmini'); }); \ No newline at end of file From f6aea0af8cf1bd56abbf8e807b3307b04c52f651 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 19:49:20 +0800 Subject: [PATCH 110/172] =?UTF-8?q?=E4=B8=8B=E5=8D=95=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E8=BF=94=E5=9B=9E=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/ErrorCode.php | 8 +++++++- app/Controller/NotifyController.php | 8 +++++++- app/Controller/OrderController.php | 5 +++-- app/Controller/PaymentController.php | 2 +- 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/app/Constants/ErrorCode.php b/app/Constants/ErrorCode.php index f6dde1c..eba612a 100644 --- a/app/Constants/ErrorCode.php +++ b/app/Constants/ErrorCode.php @@ -37,4 +37,10 @@ class ErrorCode extends AbstractConstants /** * @Message("Upload failure!") */ - const UPLOAD_INVALID = 200;} + const UPLOAD_INVALID = 200; + + /** + * @Message("Order failure!") + */ + const ORDER_FAILURE = 300; +} diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 02aa0a3..177a84d 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -6,8 +6,14 @@ use App\Constants\LogLabel; class NotifyController extends BaseController { - public function wxmini() + public function wxminiOnline() { + // 获取参数 + + // 查询订单 + + // 开始处理 + $this->log->event( LogLabel::PAY_NOTIFY_WXMINI, json_encode($this->request->input()) diff --git a/app/Controller/OrderController.php b/app/Controller/OrderController.php index 89a1cad..ff18506 100644 --- a/app/Controller/OrderController.php +++ b/app/Controller/OrderController.php @@ -2,6 +2,7 @@ namespace App\Controller; +use App\Constants\ErrorCode; use App\Request\OrderOnlineRequest; use Hyperf\Di\Annotation\Inject; use App\Service\OrderServiceInterface; @@ -20,8 +21,8 @@ class OrderController extends BaseController { $orderMainId = $this->orderService->addOnlineOrder($request->validated()); if (!is_int($orderMainId)) { - return $this->w7result(500, (string)$orderMainId); + return $this->result(ErrorCode::ORDER_FAILURE, '', $orderMainId); } - return $this->w7result(200, (string)$orderMainId); + return $this->success(['order_id' => $orderMainId]); } } \ No newline at end of file diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index 29b88e3..50202b7 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -34,7 +34,7 @@ class PaymentController extends BaseController 'body' => '懒族生活 - 外卖下单', 'out_trade_no' => $orderMain->global_order_id, 'total_fee' => bcmul(floatval($orderMain->money), 100), - 'notify_url' => config('site_host') . '/v1/notify/wxmini', + 'notify_url' => config('site_host') . '/v1/notify/wxminiOnline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); From 6a485e3a16853ff6c89262a295eefa8ffc7c004b Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 20:09:12 +0800 Subject: [PATCH 111/172] =?UTF-8?q?=E6=94=AF=E4=BB=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/ErrorCode.php | 5 +++++ app/Controller/PaymentController.php | 9 +++++++-- app/Request/WxminiPayRequest.php | 4 ++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/app/Constants/ErrorCode.php b/app/Constants/ErrorCode.php index eba612a..9ec3ba5 100644 --- a/app/Constants/ErrorCode.php +++ b/app/Constants/ErrorCode.php @@ -43,4 +43,9 @@ class ErrorCode extends AbstractConstants * @Message("Order failure!") */ const ORDER_FAILURE = 300; + + /** + * @Message("Pay failure!") + */ + const PAY_FAILURE = 400; } diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index 50202b7..da331a2 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -2,6 +2,7 @@ namespace App\Controller; +use App\Constants\ErrorCode; use App\Model\OrderMain; use App\Model\Users; use App\Request\WxminiPayRequest; @@ -22,12 +23,16 @@ class PaymentController extends BaseController // 待支付的,类型一致的,未超时(15min,900sec)的订单 $orderMain = OrderMain::query() - ->where(['state' => OrderMain::ORDER_STATE_UNPAY, 'type' => $data['type'], 'id' => $data['order_id']]) + ->where(['state' => OrderMain::ORDER_STATE_UNPAY, 'id' => $data['order_id']]) ->where('time', '<=', date('Y-m-d H:i:s', (time()-900))) ->first(); if (empty($orderMain)) { - return $this->result(200, ['order_id' => $data['order_id']],'订单不存在或已失效'); + return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单不存在或已失效'); + } + + if (floatval($orderMain->money) != floatval($data['money'])) { + return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单金额有误'); } $result = $app->order->unify([ diff --git a/app/Request/WxminiPayRequest.php b/app/Request/WxminiPayRequest.php index 2307691..633a9f5 100644 --- a/app/Request/WxminiPayRequest.php +++ b/app/Request/WxminiPayRequest.php @@ -15,8 +15,8 @@ class WxminiPayRequest extends BaseFormRequest { return [ 'order_id' => 'required|nonempty|integer', - 'type' => 'required|nonempty|integer', 'openid' => 'required|nonempty', + 'money' => 'required|nonempty', ]; } @@ -31,7 +31,7 @@ class WxminiPayRequest extends BaseFormRequest { return [ 'order_id' => '订单', - 'type' => '订单类型', + 'money' => '订单金额', 'openid' => '用户标识', ]; } From 3e95c80dd031f0ac96bbfa59c1a32bfafda4528c Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 20:27:22 +0800 Subject: [PATCH 112/172] =?UTF-8?q?=E6=94=AF=E4=BB=98=E8=8E=B7=E5=8F=96jsa?= =?UTF-8?q?pi=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index da331a2..efde0a2 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -24,17 +24,13 @@ class PaymentController extends BaseController // 待支付的,类型一致的,未超时(15min,900sec)的订单 $orderMain = OrderMain::query() ->where(['state' => OrderMain::ORDER_STATE_UNPAY, 'id' => $data['order_id']]) - ->where('time', '<=', date('Y-m-d H:i:s', (time()-900))) + ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) ->first(); if (empty($orderMain)) { return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单不存在或已失效'); } - if (floatval($orderMain->money) != floatval($data['money'])) { - return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单金额有误'); - } - $result = $app->order->unify([ 'body' => '懒族生活 - 外卖下单', 'out_trade_no' => $orderMain->global_order_id, From 91f96c88214c6b10af4d26e126d794ff4d830c29 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 21:16:12 +0800 Subject: [PATCH 113/172] =?UTF-8?q?=E6=8B=86=E5=88=86=E5=A4=96=E5=8D=96?= =?UTF-8?q?=E6=94=AF=E4=BB=98=E5=92=8C=E5=BD=93=E9=9D=A2=E6=94=AF=E4=BB=98?= =?UTF-8?q?=EF=BC=8C=E6=94=AF=E4=BB=98=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 77 +++++++++++++++++++++++++--- app/Controller/PaymentController.php | 35 +++++++++++-- config/routes.php | 6 ++- 3 files changed, 105 insertions(+), 13 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 177a84d..4794fce 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -3,20 +3,81 @@ namespace App\Controller; use App\Constants\LogLabel; +use App\Model\OrderMain; +use EasyWeChat\Factory; +use Hyperf\Guzzle\CoroutineHandler; class NotifyController extends BaseController { public function wxminiOnline() { - // 获取参数 - - // 查询订单 + $config = config('wxpay'); + $app = Factory::payment($config); + $app['guzzle_handler'] = CoroutineHandler::class; - // 开始处理 + // 通知回调,进行业务处理 + $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - $this->log->event( - LogLabel::PAY_NOTIFY_WXMINI, - json_encode($this->request->input()) - ); + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $message + ); + + // 查询订单 + $orderMain = OrderMain::query() + ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_ONLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) + ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) + ->first(); + + if (empty($orderMain)) { + // 去查一下微信订单 + $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); + + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $wxOrder + ); + + // return true; + } + }); + + $response->send(); + } + + public function wxminiOffline() + { + $config = config('wxpay'); + $app = Factory::payment($config); + $app['guzzle_handler'] = CoroutineHandler::class; + + // 通知回调,进行业务处理 + $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { + + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $message + ); + + // 查询订单 + $orderMain = OrderMain::query() + ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_OFFLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) + ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) + ->first(); + + if (empty($orderMain)) { + // 去查一下微信订单 + $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); + + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $wxOrder + ); + + // return true; + } + }); + + $response->send(); } } \ No newline at end of file diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index efde0a2..d4189dd 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -4,7 +4,6 @@ namespace App\Controller; use App\Constants\ErrorCode; use App\Model\OrderMain; -use App\Model\Users; use App\Request\WxminiPayRequest; use EasyWeChat\Factory; @@ -13,7 +12,7 @@ use Hyperf\Guzzle\CoroutineHandler; class PaymentController extends BaseController { - public function wxminiPay(WxminiPayRequest $request){ + public function wxminiPayOnline(WxminiPayRequest $request){ $data = $request->validated(); @@ -21,7 +20,7 @@ class PaymentController extends BaseController $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; - // 待支付的,类型一致的,未超时(15min,900sec)的订单 + // 待支付的,未超时(15min,900sec)的订单 $orderMain = OrderMain::query() ->where(['state' => OrderMain::ORDER_STATE_UNPAY, 'id' => $data['order_id']]) ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) @@ -43,4 +42,34 @@ class PaymentController extends BaseController return $this->success($result); } + public function wxminiPayOffline(WxminiPayRequest $request){ + + $data = $request->validated(); + + $config = config('wxpay'); + $app = Factory::payment($config); + $app['guzzle_handler'] = CoroutineHandler::class; + + // 待支付的,未超时(15min,900sec)的订单 + $orderMain = OrderMain::query() + ->where(['dm_state' => OrderMain::ORDER_STATE_UNPAY, 'id' => $data['order_id']]) + ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) + ->first(); + + if (empty($orderMain)) { + return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单不存在或已失效'); + } + + $result = $app->order->unify([ + 'body' => '懒族生活 - 当面支付', + 'out_trade_no' => $orderMain->global_order_id, + 'total_fee' => bcmul(floatval($orderMain->money), 100), + 'notify_url' => config('site_host') . '/v1/notify/wxminiOffline', + 'trade_type' => 'JSAPI', + 'openid' => $data['openid'], + ]); + + return $this->success($result); + } + } \ No newline at end of file diff --git a/config/routes.php b/config/routes.php index 2393433..266122f 100644 --- a/config/routes.php +++ b/config/routes.php @@ -41,7 +41,9 @@ Router::addGroup('/v1/',function (){ Router::post('Order/addOnline', 'App\Controller\OrderController@addOnlineOrder'); //小程序支付相关 - Router::post('wxmini/pay', 'App\Controller\PaymentController@wxminiPay'); - Router::post('notify/wxmini', 'App\Controller\NotifyController@wxmini'); + Router::post('wxminipay/online', 'App\Controller\PaymentController@wxminiPayOnline'); + Router::post('wxminipay/offline', 'App\Controller\PaymentController@wxminiPayOffline'); + Router::post('notify/wxminionline', 'App\Controller\NotifyController@wxminiOnline'); + Router::post('notify/wxminioffline', 'App\Controller\NotifyController@wxminiOffline'); }); \ No newline at end of file From 75f9eed5ceb75acb4d55ad31375ec597a5eb11c0 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 09:22:48 +0800 Subject: [PATCH 114/172] =?UTF-8?q?mark=EF=BC=9Abcmul=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E7=9A=84scale=E4=B8=8D=E8=B5=B7=E4=BD=9C=E7=94=A8=EF=BC=8C?= =?UTF-8?q?=E5=BE=97=E6=89=8B=E5=86=990?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index d4189dd..ff5159e 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -27,13 +27,13 @@ class PaymentController extends BaseController ->first(); if (empty($orderMain)) { - return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单不存在或已失效'); + return $this->result(ErrorCode::PAY_FAILURE, $data,'订单不存在或已失效'); } $result = $app->order->unify([ 'body' => '懒族生活 - 外卖下单', 'out_trade_no' => $orderMain->global_order_id, - 'total_fee' => bcmul(floatval($orderMain->money), 100), + 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), 'notify_url' => config('site_host') . '/v1/notify/wxminiOnline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], From c2ae7d892e72dd03071a1bf9d76af99021481446 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 10:01:10 +0800 Subject: [PATCH 115/172] =?UTF-8?q?=E6=94=AF=E4=BB=98=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 4 ++++ app/Controller/PaymentController.php | 10 ++++++++-- app/Service/OrderService.php | 4 ++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 4794fce..7845876 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -40,6 +40,10 @@ class NotifyController extends BaseController // return true; } + + // 修改订单、子订单状态 + + // 更新销量、商品库存,新增月销数据 }); $response->send(); diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index ff5159e..e0c850c 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -39,6 +39,9 @@ class PaymentController extends BaseController 'openid' => $data['openid'], ]); + $result['sign_type'] = 'MD5'; + $result['timestamp'] = time(); + return $this->success($result); } @@ -57,18 +60,21 @@ class PaymentController extends BaseController ->first(); if (empty($orderMain)) { - return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单不存在或已失效'); + return $this->result(ErrorCode::PAY_FAILURE, $data,'订单不存在或已失效'); } $result = $app->order->unify([ 'body' => '懒族生活 - 当面支付', 'out_trade_no' => $orderMain->global_order_id, - 'total_fee' => bcmul(floatval($orderMain->money), 100), + 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), 'notify_url' => config('site_host') . '/v1/notify/wxminiOffline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); + $result['sign_type'] = 'MD5'; + $result['timestamp'] = time(); + return $this->success($result); } diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 321c1f7..de1c925 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -83,8 +83,7 @@ class OrderService implements OrderServiceInterface // 统计订单中所有店铺当日订单数,做店铺订单序号 $countsArr = Order::query() - ->selectRaw('COUNT(*) AS count') - ->select('id') + ->selectRaw('id, COUNT(*) AS count') ->whereIn('store_id', explode(',', $dataMain['store_ids'])) ->where(['type' => OrderMain::ORDER_TYPE_ONLINE]) ->whereBetween('time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')]) @@ -93,6 +92,7 @@ class OrderService implements OrderServiceInterface $storeOrderCounts = []; foreach ($countsArr as $key => &$row) { + var_dump('row', $row); $storeOrderCounts[$row['id']] = $row['count']; } From 21a773b481b5801cacd83da6922bc41fc5c86539 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 10:28:47 +0800 Subject: [PATCH 116/172] =?UTF-8?q?=E5=9B=9E=E8=B0=83=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 63 ++++++++++++++++++++--------- 1 file changed, 44 insertions(+), 19 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 7845876..289c578 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -5,7 +5,9 @@ namespace App\Controller; use App\Constants\LogLabel; use App\Model\OrderMain; use EasyWeChat\Factory; +use Hyperf\DbConnection\Db; use Hyperf\Guzzle\CoroutineHandler; +use Exception; class NotifyController extends BaseController { @@ -18,32 +20,55 @@ class NotifyController extends BaseController // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - $this->log->event( - LogLabel::PAY_NOTIFY_WXMINI, - $message - ); - - // 查询订单 - $orderMain = OrderMain::query() - ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_ONLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) - ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) - ->first(); - - if (empty($orderMain)) { - // 去查一下微信订单 - $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); + Db::beginTransaction(); + try { $this->log->event( LogLabel::PAY_NOTIFY_WXMINI, - $wxOrder + $message ); - // return true; - } + // 查询订单 + $orderMain = OrderMain::query() + ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_ONLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) + ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) + ->first(); + + if (empty($orderMain)) { + // 去查一下微信订单 + $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); + + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $wxOrder + ); + + // return true; + } + + // 修改订单、子订单状态 + $currentTime = time(); + $orderMain->state = OrderMain::ORDER_STATE_UNTAKE; + $orderMain->time_pay = $currentTime; + $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime); + $orderMain->save(); + + // 更新销量、商品库存,新增月销数据 - // 修改订单、子订单状态 + // 喇叭通知,兼容旧音响,MQTT+IOT + + // 公众号模板消息 + + // 打印订单 + + Db::commit(); + return true; + + } catch (Exception $e) { + + Db::rollBack(); + } - // 更新销量、商品库存,新增月销数据 }); $response->send(); From 36cdb8df88cd245d003f55247e8b0cb2bf548968 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 12:34:39 +0800 Subject: [PATCH 117/172] =?UTF-8?q?=E6=94=AF=E4=BB=98=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=EF=BC=8C=E9=87=8D=E6=96=B0=E5=8A=A0=E7=AD=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 38 +++++++++++++++++++++++++--- app/Service/OrderService.php | 1 - config/config.php | 2 +- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index e0c850c..a411185 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -39,10 +39,42 @@ class PaymentController extends BaseController 'openid' => $data['openid'], ]); - $result['sign_type'] = 'MD5'; - $result['timestamp'] = time(); + $parameters = [ + 'appId' => $result['appid'], + 'timeStamp' => '' . time() . '', + 'nonceStr' => uniqid(), + 'package' => 'prepay_id=' . $result['prepay_id'], + 'signType' => 'MD5' + ]; + + //签名步骤一:按字典序排序参数 + ksort($parameters); + $string = $this->formatBizQueryParaMap($parameters, false); + //签名步骤二:在string后加入KEY + $string = $string . "&key=" . $config['key']; + //签名步骤三:MD5加密 + $string = md5($string); + //签名步骤四:所有字符转为大写 + $parameters['paySign'] = strtoupper($string); + + return $this->success($parameters); + } - return $this->success($result); + ///作用:格式化参数,签名过程需要使用 + private function formatBizQueryParaMap($paraMap, $urlencode) { + $buff = ""; + ksort($paraMap); + foreach ($paraMap as $k => $v) { + if ($urlencode) { + $v = urlencode($v); + } + $buff .= $k . "=" . $v . "&"; + } + $reqPar = null; + if (strlen($buff) > 0) { + $reqPar = substr($buff, 0, strlen($buff) - 1); + } + return $reqPar; } public function wxminiPayOffline(WxminiPayRequest $request){ diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index de1c925..54468a9 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -92,7 +92,6 @@ class OrderService implements OrderServiceInterface $storeOrderCounts = []; foreach ($countsArr as $key => &$row) { - var_dump('row', $row); $storeOrderCounts[$row['id']] = $row['count']; } diff --git a/config/config.php b/config/config.php index c67f910..7e8d490 100644 --- a/config/config.php +++ b/config/config.php @@ -32,7 +32,7 @@ return [ 'wxpay' => [ 'app_id' => env('APP_ID',''), 'mch_id' => env('MCH_ID',''), - 'key' => env('APP_SECRET',''), + 'key' => env('MCH_KEY',''), 'cert_path' => env('CERT_PATH',''), 'key_path' => env('KEY_PATH',''), 'notify_url' => env('NOTIFY_URL',''), From 8af4a94909af7c9ee8cc5da03e0b683d38055b50 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 13:05:49 +0800 Subject: [PATCH 118/172] =?UTF-8?q?=E4=B8=8B=E5=8D=95=E6=94=AF=E4=BB=98?= =?UTF-8?q?=EF=BC=9A=E7=BA=BF=E4=B8=8A=E3=80=81=E7=BA=BF=E4=B8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 81 ++++++++++++++++++---------- 1 file changed, 52 insertions(+), 29 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index a411185..f8d36fd 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -39,6 +39,7 @@ class PaymentController extends BaseController 'openid' => $data['openid'], ]); + // 返回支付参数给前端 $parameters = [ 'appId' => $result['appid'], 'timeStamp' => '' . time() . '', @@ -47,36 +48,11 @@ class PaymentController extends BaseController 'signType' => 'MD5' ]; - //签名步骤一:按字典序排序参数 - ksort($parameters); - $string = $this->formatBizQueryParaMap($parameters, false); - //签名步骤二:在string后加入KEY - $string = $string . "&key=" . $config['key']; - //签名步骤三:MD5加密 - $string = md5($string); - //签名步骤四:所有字符转为大写 - $parameters['paySign'] = strtoupper($string); + $parameters['paySign'] = $this->signture($parameters, $config['key']); return $this->success($parameters); } - ///作用:格式化参数,签名过程需要使用 - private function formatBizQueryParaMap($paraMap, $urlencode) { - $buff = ""; - ksort($paraMap); - foreach ($paraMap as $k => $v) { - if ($urlencode) { - $v = urlencode($v); - } - $buff .= $k . "=" . $v . "&"; - } - $reqPar = null; - if (strlen($buff) > 0) { - $reqPar = substr($buff, 0, strlen($buff) - 1); - } - return $reqPar; - } - public function wxminiPayOffline(WxminiPayRequest $request){ $data = $request->validated(); @@ -104,10 +80,57 @@ class PaymentController extends BaseController 'openid' => $data['openid'], ]); - $result['sign_type'] = 'MD5'; - $result['timestamp'] = time(); + // 返回支付参数给前端 + $parameters = [ + 'appId' => $result['appid'], + 'timeStamp' => '' . time() . '', + 'nonceStr' => uniqid(), + 'package' => 'prepay_id=' . $result['prepay_id'], + 'signType' => 'MD5' + ]; + + $parameters['paySign'] = $this->signture($parameters, $config['key']); + + return $this->success($parameters); + } + + /** + * 支付参数加签 + * @param $parameters + * @param $key + * @return string + */ + private function signture($parameters, $key) + { + // 按字典序排序参数 + ksort($parameters); + + // http_query + $queryParams = $this->http_query($parameters); + + // 加入KEY + $queryParams = $queryParams . "&key=" . $key; + + // MD5加密 + $queryParams = md5($queryParams); + + // 字符转为大写 + return strtoupper($queryParams); + } + + /** + * 参数转为http query字串 + * @param $parameters + * @return string + */ + private function http_query($parameters) { + + $http_query = []; + foreach ($parameters as $key => $value) { + $http_query[] = $key.'='.$value; + } - return $this->success($result); + return implode('&', $http_query); } } \ No newline at end of file From 4a11341c8eded80b9983572ffed0913fc2941cda Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 14:32:19 +0800 Subject: [PATCH 119/172] =?UTF-8?q?=E6=94=AF=E4=BB=98=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index f8d36fd..a3ffbd6 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -33,8 +33,9 @@ class PaymentController extends BaseController $result = $app->order->unify([ 'body' => '懒族生活 - 外卖下单', 'out_trade_no' => $orderMain->global_order_id, - 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), - 'notify_url' => config('site_host') . '/v1/notify/wxminiOnline', + // 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), + 'total_fee' => 1, + 'notify_url' => config('site_host') . '/v1/notify/wxminionline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); @@ -75,7 +76,7 @@ class PaymentController extends BaseController 'body' => '懒族生活 - 当面支付', 'out_trade_no' => $orderMain->global_order_id, 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), - 'notify_url' => config('site_host') . '/v1/notify/wxminiOffline', + 'notify_url' => config('site_host') . '/v1/notify/wxminioffline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); From 232b3c48830136cfa8e8a1d9d43cfe54af2aae0e Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Thu, 13 Aug 2020 17:04:08 +0800 Subject: [PATCH 120/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E6=8E=A5=E5=8F=A3-=E6=9F=A5=E8=AF=A2=E6=9D=A1?= =?UTF-8?q?=E6=95=B0=E4=B8=8D=E9=99=90=E5=88=B6=E5=92=8C=E5=85=B6=E4=BB=96?= =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + app/Controller/CouponController.php | 4 ++-- app/Controller/CouponRebateController.php | 11 ++------- app/Service/CouponService.php | 27 ++++++++++++++++++----- config/autoload/dependencies.php | 1 + 5 files changed, 27 insertions(+), 17 deletions(-) diff --git a/.gitignore b/.gitignore index 9091e68..9454e2b 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ vendor/ *.lock .phpunit* /watch +.vscode/ diff --git a/app/Controller/CouponController.php b/app/Controller/CouponController.php index 6212782..648039a 100644 --- a/app/Controller/CouponController.php +++ b/app/Controller/CouponController.php @@ -20,13 +20,13 @@ use Hyperf\DbConnection\Db; use Hyperf\Redis\Redis; use Hyperf\Utils\ApplicationContext; use App\Request\CouponGetListRequest; -use App\Service\CouponService; +use App\Service\CouponServiceInterface; class CouponController extends BaseController { /** * @Inject - * @var CouponService + * @var CouponServiceInterface */ protected $couponService; diff --git a/app/Controller/CouponRebateController.php b/app/Controller/CouponRebateController.php index 3f4064b..7765de3 100644 --- a/app/Controller/CouponRebateController.php +++ b/app/Controller/CouponRebateController.php @@ -11,24 +11,17 @@ declare(strict_types=1); */ namespace App\Controller; -use Hyperf\DbConnection\Db; -use Hyperf\Redis\Redis; -use Hyperf\Utils\ApplicationContext; + use App\Service\CouponRebateServiceInterface; -use http\Client\Curl\User; use Hyperf\Di\Annotation\Inject; -use App\Model\Coupon; -use App\Model\CouponUserRecType; -use App\Model\CouponRec; use App\Request\CouponRebateReceiveRequest; -use App\Service\CouponRebateService; use App\Request\CouponRebateTieRequest; class CouponRebateController extends BaseController { /** * @Inject - * @var CouponRebateService + * @var CouponRebateServiceInterface */ protected $CouponRebateService; diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 994b899..9fc4f97 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -13,6 +13,7 @@ use App\Constants\SsdbKeysPrefix; use App\Constants\LogLabel; use App\Commons\Log; use Exception; +use App\Service\CommonService; class CouponService implements CouponServiceInterface { @@ -21,6 +22,12 @@ class CouponService implements CouponServiceInterface * @var Log */ protected $log; + + /** + * @Inject + * @var CommonService + */ + protected $commonService; /** * 获取用户可领取优惠卷接口 @@ -45,13 +52,17 @@ class CouponService implements CouponServiceInterface ]; $nowTime = time(); $c_ids = []; - + $whereC = [ + ['end_time','>',$nowTime], + ['start_time','<=',$nowTime], + ['status','=',1] + ]; // 渠道开启,查询该渠道可以领取的优惠券ID // 渠道未开启,查询所有优惠券 if (env('SUB_CHANNEL') == 1) { - $c_ids = CouponUserRecType::where('receive_type', $receiveType)->pluck('system_coupon_user_id'); + $c_ids = CouponUserRecType::where('receive_type', $receiveType)->where($whereC)->pluck('system_coupon_user_id'); } else { - $c_ids = Coupon::pluck('id'); + $c_ids = Coupon::where($whereC)->pluck('id'); } $couponReceive = CouponRec::where('user_id',$userId); @@ -71,13 +82,17 @@ class CouponService implements CouponServiceInterface $couponIds = array_diff($c_ids, $cr_ids); // 转发型优惠券 - $couponReceiveIds = $couponActivity === false ? [] : explode(',',$couponActivity['forward']); + $couponReceiveIds = ($couponActivity === false || $this->commonService->empty($couponActivity['forward']) )? [] : explode(',',$couponActivity['forward']); + // 所有优惠券 + $couponIds = array_merge($couponIds,$couponReceiveIds); $whereC = [ ['u.end_time','>',$nowTime], ['u.start_time','<=',$nowTime], ['u.status','=',1] ]; + // 查询领取型1 和 转发型2 + $whereActiveType = [1,2]; if (env('SUB_CHANNEL') == 1) { array_push($whereC, ['type.receive_type','=', $receiveType]); @@ -86,16 +101,16 @@ class CouponService implements CouponServiceInterface $coupons = Db::table('ims_system_coupon_user as u') ->join('ims_system_coupon_user_receivetype as type', 'u.id', '=', 'type.system_coupon_user_id') ->whereIn('u.id', $couponIds) + ->whereIn('u.active_type', $whereActiveType) ->where($whereC) ->whereRaw('u.inventory_use < u.inventory and u.inventory-u.inventory_use >= type.one_receive_number') ->select('u.*','type.one_receive_number') ->orderBy('u.weigh','desc') - ->limit(4) ->get(); foreach ($coupons as $k => &$v){ - if($v->active_type == 1){ + if($v->active_type == 1 && count($result['not_receive']) < 4){ $result['not_receive'][] = $v; }else if($v->active_type == 2 && in_array($v->id,$couponReceiveIds)){ $result['jump_data']['coupons'][] = $v->id; diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 2b8b2ad..28a2970 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -17,4 +17,5 @@ return [ \App\Commons\Log::class => \App\Commons\Log::class, \App\Service\CouponRebateServiceInterface::class => \App\Service\CouponRebateService::class, \App\Service\UserServiceInterface::class => \App\Service\UserService::class, + \App\Service\CouponServiceInterface::class => \App\Service\CouponService::class, ]; From d6d23fdce496f1e1bdf703acf65e9cdf73e3945c Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 21:32:37 +0800 Subject: [PATCH 121/172] =?UTF-8?q?=E7=BA=BF=E4=B8=8A=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 4 +- app/Controller/DeviceController.php | 4 +- app/Controller/NotifyController.php | 179 ++++++++-- app/Controller/OrderController.php | 10 + app/Controller/PaymentController.php | 1 - app/Controller/TestController.php | 35 +- app/Libs/FeiePrintClient.php | 307 ++++++++++++++++++ app/Model/OrderMain.php | 1 + app/Model/OrderSalesStatistic.php | 29 ++ app/Model/SystemConfig.php | 10 + app/Request/OrderOfflineRequest.php | 42 +++ app/Service/CouponService.php | 2 +- ...terface.php => CouponServiceInterface.php} | 2 +- app/Service/DeviceServiceImp.php | 45 ++- ...terFace.php => DeviceServiceInterface.php} | 3 +- app/Service/FeiePrintService.php | 226 +++++++++++++ app/Service/FeiePrintServiceInterface.php | 10 + app/Service/MiniprogramService.php | 147 +++++++++ app/Service/MiniprogramServiceInterface.php | 9 + app/Service/MqttServiceInterface.php | 21 ++ app/Service/MqttSpeakerService.php | 48 +++ app/Service/OrderService.php | 107 +++++- app/Service/OrderServiceInterface.php | 2 +- app/TaskWorker/MQTTClientTask.php | 40 ++- config/autoload/dependencies.php | 7 +- config/config.php | 5 +- config/routes.php | 1 + 27 files changed, 1240 insertions(+), 57 deletions(-) create mode 100644 app/Libs/FeiePrintClient.php create mode 100644 app/Model/OrderSalesStatistic.php create mode 100644 app/Model/SystemConfig.php create mode 100644 app/Request/OrderOfflineRequest.php rename app/Service/{CoupnoServiceInterface.php => CouponServiceInterface.php} (93%) rename app/Service/{DeviceServiceInterFace.php => DeviceServiceInterface.php} (68%) create mode 100644 app/Service/FeiePrintService.php create mode 100644 app/Service/FeiePrintServiceInterface.php create mode 100644 app/Service/MiniprogramService.php create mode 100644 app/Service/MiniprogramServiceInterface.php create mode 100644 app/Service/MqttServiceInterface.php create mode 100644 app/Service/MqttSpeakerService.php diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index f6e58bc..08a2d1c 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -6,7 +6,7 @@ namespace App\Amqp\Consumer; use App\Model\Order; use App\Model\SpeakerDevic; -use App\Service\DeviceServiceInterFace; +use App\Service\DeviceServiceInterface; use Hyperf\Amqp\Result; use Hyperf\Amqp\Annotation\Consumer; use Hyperf\Amqp\Message\ConsumerMessage; @@ -21,7 +21,7 @@ class DevicOrderConsumer extends ConsumerMessage { /** * @Inject - * @var DeviceServiceInterFace + * @var DeviceServiceInterface */ protected $deviceService; diff --git a/app/Controller/DeviceController.php b/app/Controller/DeviceController.php index ee315b3..d7ec213 100644 --- a/app/Controller/DeviceController.php +++ b/app/Controller/DeviceController.php @@ -4,7 +4,7 @@ namespace App\Controller; use Hyperf\Di\Annotation\Inject; use App\Exception\BusinessException; -use App\Service\DeviceServiceInterFace; +use App\Service\DeviceServiceInterface; use Hyperf\Validation\ValidationException; class DeviceController extends BaseController @@ -12,7 +12,7 @@ class DeviceController extends BaseController /** * @Inject - * @var DeviceServiceInterFace + * @var DeviceServiceInterface */ protected $deviceService; diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 289c578..3ac5cd3 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -3,46 +3,114 @@ namespace App\Controller; use App\Constants\LogLabel; +use App\Model\Goods; +use App\Model\Order; +use App\Model\OrderGoods; use App\Model\OrderMain; +use App\Model\OrderSalesStatistic; +use App\Model\SpecCombination; +use App\Model\Store; +use App\Model\SystemConfig; +use App\Service\DeviceServiceInterface; +use App\Service\FeiePrintServiceInterface; +use App\Service\MiniprogramService; +use App\Service\MqttServiceInterface; use EasyWeChat\Factory; use Hyperf\DbConnection\Db; use Hyperf\Guzzle\CoroutineHandler; use Exception; +use Hyperf\Di\Annotation\Inject; class NotifyController extends BaseController { + + /** + * @Inject + * @var MqttServiceInterface + */ + protected $mqttSpeakerService; + + /** + * @Inject + * @var DeviceServiceInterface + */ + protected $deviceService; + + /** + * @Inject + * @var MiniprogramService + */ + protected $miniprogramService; + + /** + * @Inject + * @var FeiePrintServiceInterface + */ + protected $feiePrintService; + public function wxminiOnline() { + $config = config('wxpay'); $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; - + var_dump('inside'); // 通知回调,进行业务处理 - $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - - Db::beginTransaction(); - try { - - $this->log->event( - LogLabel::PAY_NOTIFY_WXMINI, - $message - ); + Db::beginTransaction(); + try { + $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { + + var_dump('message', $message); + // 支付失败或者通知失败 + if ( + empty($message) + || $message['return_code'] != 'SUCCESS' + || !isset($message['result_code']) + || $message['result_code'] != 'SUCCESS' + ) { + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $message + ); + $fail('Unknown error but FAIL'); + } // 查询订单 $orderMain = OrderMain::query() - ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_ONLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) - ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) + ->where([ + 'global_order_id' => $message['out_trade_no'], + 'type' => OrderMain::ORDER_TYPE_ONLINE, + 'state' => OrderMain::ORDER_STATE_UNPAY + ]) + ->where('time', '>=', date('Y-m-d H:i:s', (time() - 900))) ->first(); - + var_dump('$orderMain', $orderMain); + // 订单不存在 if (empty($orderMain)) { - // 去查一下微信订单 - $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); $this->log->event( LogLabel::PAY_NOTIFY_WXMINI, - $wxOrder + $orderMain ); + // 去查一下微信订单,只处理未支付的情况 TODO 其他情况处理 + $wxOrder = $app->order->queryByOutTradeNumber($message['out_trade_no']); + // 查询成功 + if ($wxOrder['return_code'] == 'SUCCESS') { + if ($wxOrder['result_code'] == 'SUCCESS') { + // 看订单支付状态,处理未支付的情况,把订单处理成未支付 + if ($wxOrder['trade_state'] != 'NOTPAY') { + OrderMain::query() + ->where(['global_order_id' => $message['out_trade_no']]) + ->update(['state' => OrderMain::ORDER_STATE_UNPAY]); + + $fail('Order not paid'); + } + } + } + + + // return true; } @@ -53,25 +121,86 @@ class NotifyController extends BaseController $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime); $orderMain->save(); - // 更新销量、商品库存,新增月销数据 + $upOrder = Order::query() + ->where(['order_main_id' => $orderMain->id]) + ->update(['state' => OrderMain::ORDER_STATE_UNTAKE, 'pay_time' => $orderMain->pay_time]); + + // 更新商户销量 + $upStoreScore = Store::query() + ->whereIn('id', $orderMain->order_ids) + ->update(['score' => Db::raw('score+1')]); + + // 更新商品库存和销量 + $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'createtime']) + ->where(['order_main_id' => $orderMain->id]) + ->get() + ->toArray(); + $orderGoods = OrderGoods::query()->select(['good_id AS id', 'number', 'combination_id']) + ->whereIn('order_id', array_values(array_column($orders, 'id'))) + ->get() + ->toArray(); + foreach ($orderGoods as $key => &$goodsItem) { + + $goods = Goods::find($goodsItem['id']); + + // 库存处理,有规格 + if ($goodsItem->combination_id) { + $combination = SpecCombination::find($goodsItem['combination_id']); + $combination->number = $combination->number - $goodsItem['number']; + $combination->save(); + } else { + $goods->inventory = $goods->inventory - $goodsItem['number']; + } + + $goods->sales = $goods->sales - $goodsItem['number']; + $goods->save(); + + } + + // 月销流水 + $statistics = []; + foreach ($orders as $key => & $order) { + $statistics[] = [ + 'money' => $order->money, + 'user_id' => $order->user_id, + 'store_id' => $order->store_id, + 'market_id' => $orderMain->market_id, + 'order_id' => $order->id, + 'createtime' => strtotime($order->pay_time), + ]; + } + + if (is_array($statistics) && !empty($statistics)) { + $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics); + } // 喇叭通知,兼容旧音响,MQTT+IOT + $res = $this->mqttSpeakerService->speakToStore($orderMain->id); + var_dump($res); + $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); + var_dump($res); // 公众号模板消息 + $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); + var_dump($res); - // 打印订单 + // 打印订单,自动打印 TODO 后续优化调用逻辑 + $res = $this->feiePrintService->feiePrint($orderMain->order_num); + var_dump($res); - Db::commit(); - return true; + }); - } catch (Exception $e) { + var_dump('$response', $response); + Db::rollBack(); + $response->send(); - Db::rollBack(); - } + } catch (\EasyWeChat\Kernel\Exceptions\Exception $e) { - }); + var_dump($e->getMessage()); + Db::rollBack(); + + } - $response->send(); } public function wxminiOffline() diff --git a/app/Controller/OrderController.php b/app/Controller/OrderController.php index ff18506..f26045d 100644 --- a/app/Controller/OrderController.php +++ b/app/Controller/OrderController.php @@ -3,6 +3,7 @@ namespace App\Controller; use App\Constants\ErrorCode; +use App\Request\OrderOfflineRequest; use App\Request\OrderOnlineRequest; use Hyperf\Di\Annotation\Inject; use App\Service\OrderServiceInterface; @@ -25,4 +26,13 @@ class OrderController extends BaseController } return $this->success(['order_id' => $orderMainId]); } + + public function addOfflineOrder(OrderOfflineRequest $request) + { + $orderMainId = $this->orderService->addOfflineOrder($request->validated()); + if (!is_int($orderMainId)) { + return $this->result(ErrorCode::ORDER_FAILURE, '', $orderMainId); + } + return $this->success(['order_id' => $orderMainId]); + } } \ No newline at end of file diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index a3ffbd6..5047f27 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -65,7 +65,6 @@ class PaymentController extends BaseController // 待支付的,未超时(15min,900sec)的订单 $orderMain = OrderMain::query() ->where(['dm_state' => OrderMain::ORDER_STATE_UNPAY, 'id' => $data['order_id']]) - ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) ->first(); if (empty($orderMain)) { diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index f69cea8..10fe872 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Controller; +use App\Libs\FeiePrintClient; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Annotation\AutoController; use Hyperf\Utils\Coroutine; @@ -22,6 +23,7 @@ class TestController extends AbstractController { private $name = 'default action'; + protected $client = null; public function index1(RequestInterface $request) { @@ -37,14 +39,33 @@ class TestController extends AbstractController // $result = $client->handle("set"); - //$log = ApplicationContext::getContainer()->get(Log::class); - $log = $this->log; - - $log->push(['test'=>1,'user_id'=>290,'msg'=>'order']); - $log->event('t1',['test'=>1,'user_id'=>290,'msg'=>'order']); + // //$log = ApplicationContext::getContainer()->get(Log::class); + // $log = $this->log; + // + // $log->push(['test'=>1,'user_id'=>290,'msg'=>'order']); + // $log->event('t1',['test'=>1,'user_id'=>290,'msg'=>'order']); + // + // //$this->name = 'index1 action '. $result; + // return $this->name; - //$this->name = 'index1 action '. $result; - return $this->name; + $time = time(); + $msgInfo = array( + 'user' => '13161443713@163.com', + 'stime' => $time, + 'sig' => sha1('13161443713@163.com' . 'XsaHzgePdyWTfcMX' . $time), + 'apiname' => 'Open_printMsg', + 'sn' => '920527381', + 'content' => '1111', + 'times' => 1//打印次数 + ); + $this->client = new FeiePrintClient('api.feieyun.cn', 80); + if (!$this->client->post('/Api/Open/', $msgInfo)) { + return '12'; + } else { + //服务器返回的JSON字符串,建议要当做日志记录起来 + $result = $this->client->getContent(); + return $result; + } } public function index2(RequestInterface $request) diff --git a/app/Libs/FeiePrintClient.php b/app/Libs/FeiePrintClient.php new file mode 100644 index 0000000..a1b4789 --- /dev/null +++ b/app/Libs/FeiePrintClient.php @@ -0,0 +1,307 @@ +host = $host; + $this->port = $port; + } + function get($path, $data = false) { + $this->path = $path; + $this->method = 'GET'; + if ($data) { + $this->path .= '?'.$this->buildQueryString($data); + } + return $this->doRequest(); + } + function post($path, $data) { + $this->path = $path; + $this->method = 'POST'; + $this->postdata = $this->buildQueryString($data); + return $this->doRequest(); + } + function buildQueryString($data) { + $querystring = ''; + if (is_array($data)) { + foreach ($data as $key => $val) { + if (is_array($val)) { + foreach ($val as $val2) { + $querystring .= urlencode($key).'='.urlencode($val2).'&'; + } + } else { + $querystring .= urlencode($key).'='.urlencode($val).'&'; + } + } + $querystring = substr($querystring, 0, -1); // Eliminate unnecessary & + } else { + $querystring = $data; + } + return $querystring; + } + function doRequest() { + if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) { + switch($errno) { + case -3: + $this->errormsg = 'Socket creation failed (-3)'; + case -4: + $this->errormsg = 'DNS lookup failure (-4)'; + case -5: + $this->errormsg = 'Connection refused or timed out (-5)'; + default: + $this->errormsg = 'Connection failed ('.$errno.')'; + $this->errormsg .= ' '.$errstr; + $this->debug($this->errormsg); + } + return false; + } + socket_set_timeout($fp, $this->timeout); + $request = $this->buildRequest(); + $this->debug('Request', $request); + fwrite($fp, $request); + $this->headers = array(); + $this->content = ''; + $this->errormsg = ''; + $inHeaders = true; + $atStart = true; + while (!feof($fp)) { + $line = fgets($fp, 4096); + if ($atStart) { + $atStart = false; + if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) { + $this->errormsg = "Status code line invalid: ".htmlentities($line); + $this->debug($this->errormsg); + return false; + } + $http_version = $m[1]; + $this->status = $m[2]; + $status_string = $m[3]; + $this->debug(trim($line)); + continue; + } + if ($inHeaders) { + if (trim($line) == '') { + $inHeaders = false; + $this->debug('Received Headers', $this->headers); + if ($this->headers_only) { + break; + } + continue; + } + if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) { + continue; + } + $key = strtolower(trim($m[1])); + $val = trim($m[2]); + if (isset($this->headers[$key])) { + if (is_array($this->headers[$key])) { + $this->headers[$key][] = $val; + } else { + $this->headers[$key] = array($this->headers[$key], $val); + } + } else { + $this->headers[$key] = $val; + } + continue; + } + $this->content .= $line; + } + fclose($fp); + if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') { + $this->debug('Content is gzip encoded, unzipping it'); + $this->content = substr($this->content, 10); + $this->content = gzinflate($this->content); + } + if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) { + $cookies = $this->headers['set-cookie']; + if (!is_array($cookies)) { + $cookies = array($cookies); + } + foreach ($cookies as $cookie) { + if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) { + $this->cookies[$m[1]] = $m[2]; + } + } + $this->cookie_host = $this->host; + } + if ($this->persist_referers) { + $this->debug('Persisting referer: '.$this->getRequestURL()); + $this->referer = $this->getRequestURL(); + } + if ($this->handle_redirects) { + if (++$this->redirect_count >= $this->max_redirects) { + $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')'; + $this->debug($this->errormsg); + $this->redirect_count = 0; + return false; + } + $location = isset($this->headers['location']) ? $this->headers['location'] : ''; + $uri = isset($this->headers['uri']) ? $this->headers['uri'] : ''; + if ($location || $uri) { + $url = parse_url($location.$uri); + return $this->get($url['path']); + } + } + return true; + } + function buildRequest() { + $headers = array(); + $headers[] = "{$this->method} {$this->path} HTTP/1.0"; + $headers[] = "Host: {$this->host}"; + $headers[] = "User-Agent: {$this->user_agent}"; + $headers[] = "Accept: {$this->accept}"; + if ($this->use_gzip) { + $headers[] = "Accept-encoding: {$this->accept_encoding}"; + } + $headers[] = "Accept-language: {$this->accept_language}"; + if ($this->referer) { + $headers[] = "Referer: {$this->referer}"; + } + if ($this->cookies) { + $cookie = 'Cookie: '; + foreach ($this->cookies as $key => $value) { + $cookie .= "$key=$value; "; + } + $headers[] = $cookie; + } + if ($this->username && $this->password) { + $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password); + } + if ($this->postdata) { + $headers[] = 'Content-Type: application/x-www-form-urlencoded'; + $headers[] = 'Content-Length: '.strlen($this->postdata); + } + $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata; + return $request; + } + function getStatus() { + return $this->status; + } + function getContent() { + return $this->content; + } + function getHeaders() { + return $this->headers; + } + function getHeader($header) { + $header = strtolower($header); + if (isset($this->headers[$header])) { + return $this->headers[$header]; + } else { + return false; + } + } + function getError() { + return $this->errormsg; + } + function getCookies() { + return $this->cookies; + } + function getRequestURL() { + $url = 'https://'.$this->host; + if ($this->port != 80) { + $url .= ':'.$this->port; + } + $url .= $this->path; + return $url; + } + function setUserAgent($string) { + $this->user_agent = $string; + } + function setAuthorization($username, $password) { + $this->username = $username; + $this->password = $password; + } + function setCookies($array) { + $this->cookies = $array; + } + function useGzip($boolean) { + $this->use_gzip = $boolean; + } + function setPersistCookies($boolean) { + $this->persist_cookies = $boolean; + } + function setPersistReferers($boolean) { + $this->persist_referers = $boolean; + } + function setHandleRedirects($boolean) { + $this->handle_redirects = $boolean; + } + function setMaxRedirects($num) { + $this->max_redirects = $num; + } + function setHeadersOnly($boolean) { + $this->headers_only = $boolean; + } + function setDebug($boolean) { + $this->debug = $boolean; + } + function quickGet($url) { + $bits = parse_url($url); + $host = $bits['host']; + $port = isset($bits['port']) ? $bits['port'] : 80; + $path = isset($bits['path']) ? $bits['path'] : '/'; + if (isset($bits['query'])) { + $path .= '?'.$bits['query']; + } + $client = new HttpClient($host, $port); + if (!$client->get($path)) { + return false; + } else { + return $client->getContent(); + } + } + function quickPost($url, $data) { + $bits = parse_url($url); + $host = $bits['host']; + $port = isset($bits['port']) ? $bits['port'] : 80; + $path = isset($bits['path']) ? $bits['path'] : '/'; + $client = new HttpClient($host, $port); + if (!$client->post($path, $data)) { + return false; + } else { + return $client->getContent(); + } + } + function debug($msg, $object = false) { + if ($this->debug) { + print '
HttpClient Debug: '.$msg; + if ($object) { + ob_start(); + print_r($object); + $content = htmlentities(ob_get_contents()); + ob_end_clean(); + print '
'.$content.'
'; + } + print '
'; + } + } +} \ No newline at end of file diff --git a/app/Model/OrderMain.php b/app/Model/OrderMain.php index ee3840c..4972484 100644 --- a/app/Model/OrderMain.php +++ b/app/Model/OrderMain.php @@ -75,6 +75,7 @@ class OrderMain extends Model 'coupon_id2', 'uniacid', 'state', + 'dm_state', 'time', 'time_add', 'pay_time', diff --git a/app/Model/OrderSalesStatistic.php b/app/Model/OrderSalesStatistic.php new file mode 100644 index 0000000..a20edf8 --- /dev/null +++ b/app/Model/OrderSalesStatistic.php @@ -0,0 +1,29 @@ + 'required|nonempty|integer', + 'user_id' => 'required|nonempty|integer', + 'money' => 'required|nonempty', + ]; + } + + public function messages(): array + { + return [ + '*.*' => ':attribute 参数异常' + ]; + } + + public function attributes(): array + { + return [ + + ]; + } +} diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index f4f8af9..227d79b 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -6,7 +6,7 @@ use Hyperf\DbConnection\Db; use Hyperf\Redis\Redis; use Hyperf\Utils\ApplicationContext; -class CouponService implements CoupnoServiceInterface +class CouponService implements CouponServiceInterface { /** diff --git a/app/Service/CoupnoServiceInterface.php b/app/Service/CouponServiceInterface.php similarity index 93% rename from app/Service/CoupnoServiceInterface.php rename to app/Service/CouponServiceInterface.php index 4e3d9a4..943eb38 100644 --- a/app/Service/CoupnoServiceInterface.php +++ b/app/Service/CouponServiceInterface.php @@ -4,7 +4,7 @@ namespace App\Service; -interface CoupnoServiceInterface +interface CouponServiceInterface { /** * 当前订单可用优惠券列表 diff --git a/app/Service/DeviceServiceImp.php b/app/Service/DeviceServiceImp.php index 2b4962c..16c9110 100644 --- a/app/Service/DeviceServiceImp.php +++ b/app/Service/DeviceServiceImp.php @@ -4,13 +4,14 @@ namespace App\Service; use App\Commons\Log; use App\Constants\LogLabel; +use App\Model\Order; use App\Model\SpeakerDevic; use App\Model\Store; use Hyperf\Di\Annotation\Inject; use Hyperf\Utils\ApplicationContext; use App\TaskWorker\AliIotTask; -class DeviceServiceImp implements DeviceServiceInterFace +class DeviceServiceImp implements DeviceServiceInterface { /** * @Inject @@ -54,13 +55,6 @@ class DeviceServiceImp implements DeviceServiceInterFace // 获取市场ID $market_id = Store::query()->where(['id' => $store_id])->value('market_id'); - // $sd = new SpeakerDevic; - // $sd->store_id = $store_id; - // $sd->device_name = $dev_name; - // $sd->market_id = $market_id; - // $sd->bind_time = time(); - // $sd->saveOrFail(); - $sd = SpeakerDevic::query()->updateOrCreate( ['store_id' => $store_id, 'device_name' => $dev_name], ['market_id' => $market_id, 'bind_time' => time(), 'is_bind' => SpeakerDevic::IS_BIND_YES] @@ -84,8 +78,9 @@ class DeviceServiceImp implements DeviceServiceInterFace /** * 发布语音消息 - * @param $store_id + * @param $dev_names * @param $msg + * @return bool */ public function pubMsgToStoreByDevName($dev_names, $msg) { @@ -96,6 +91,38 @@ class DeviceServiceImp implements DeviceServiceInterFace return true; } + public function pubMsgToStoreByOrderMainId($order_id, $is_main = true) + { + + // 获取订单 + $orders = Order::query()->select(['id','order_num','money', 'pay_type', 'store_id', 'type']); + if ($is_main) { + $orders = $orders->where(['order_main_id' => $order_id])->get()->toArray(); + } else { + $orders = $orders->where(['id' => $order_id])->get()->toArray(); + } + + if(empty($orders)) return; + + // 循环发送 + foreach ($orders as $k => &$order) { + + $device_names = SpeakerDevic::query() + ->select(['device_name']) + ->where(['store_id' => $order['store_id'], 'is_bind' => SpeakerDevic::IS_BIND_YES]) + ->get() + ->toArray(); + + $msg = "{\"msg\":\"到账".$order['money']."元\"}"; + foreach ($device_names as $key => $dev_name) { + $this->IOTService->pub($dev_name['device_name'], $msg); + } + } + + return true; + + } + /** * 当前设备是否已经被绑定 * @param $dev_name diff --git a/app/Service/DeviceServiceInterFace.php b/app/Service/DeviceServiceInterface.php similarity index 68% rename from app/Service/DeviceServiceInterFace.php rename to app/Service/DeviceServiceInterface.php index 15aa23b..68cd47c 100644 --- a/app/Service/DeviceServiceInterFace.php +++ b/app/Service/DeviceServiceInterface.php @@ -2,10 +2,11 @@ namespace App\Service; -interface DeviceServiceInterFace +interface DeviceServiceInterface { public function getListByStoreId($store_id); public function bindByStoreId($dev_name,$store_id); public function unbindById($bind_id); public function pubMsgToStoreByDevName($dev_names,$msg); + public function pubMsgToStoreByOrderMainId($order_id, $is_main = true); } \ No newline at end of file diff --git a/app/Service/FeiePrintService.php b/app/Service/FeiePrintService.php new file mode 100644 index 0000000..b822175 --- /dev/null +++ b/app/Service/FeiePrintService.php @@ -0,0 +1,226 @@ +join('ims_cjdc_order as o','o.order_main_id', '=', 'm.id','inner') + ->join('ims_cjdc_order_goods as g','o.id','=', 'g.order_id','inner') + ->join('ims_cjdc_feprint as f','m.market_id','=', 'f.market_id','inner') + ->join('ims_cjdc_store as s','s.id','=', 'o.store_id','inner') + ->where('m.order_num', $order_num) + ->select("o.note as o_note,g.name,g.number,g.money,g.good_unit,m.delivery_time as ps_time,m.address,m.note,m.name as user_name,m.dada_fee,m.money as m_money,m.yhq_money2,m.box_money,f.sn,m.tel,m.order_num,g.id,g.spec,s.name as shopname") + ->order('s.id') + ->get(); + + $content = $this->printFormat($data, 14, 6, 3, 6); + $res = $this->printMsg($data[0]['sn'], $content, 1); + return ($res); + } + + /** + * [打印订单接口 Open_printMsg] + * @param [string] $sn [打印机编号sn] + * @param [string] $content [打印内容] + * @param [string] $times [打印联数] + * @return [string] [接口返回值] + */ + protected function printMsg($sn, $content, $times = 1) + { + $time = time(); //请求时间 + $msgInfo = array( + 'user' => self::USER, + 'stime' => $time, + 'sig' => sha1(self::USER . self::UKEY . $time), + 'apiname' => 'Open_printMsg', + 'sn' => $sn, + 'content' => $content, + 'times' => $times//打印次数 + ); + + $client = new FeiePrintClient(self::IP, self::PORT); + if (!$client->post(self::PATH, $msgInfo)) { + echo 'error'; + } else { + // 服务器返回的JSON字符串,建议要当做日志记录起来 + $result = $client->getContent(); + return $result; + } + } + + protected function printFormat($arr, $A, $B, $C, $D) + { + $orderInfo = '懒族生活
'; + $orderInfo .= '名称 单价 数量 金额
'; + $orderInfo .= '--------------------------------
'; + $shopname = ""; + $shopnum = 0; + foreach ($arr as $k5 => $v5) { + if ($shopname != $v5['shopname']) { + if ($shopname != "") { + $orderInfo .= '
'; + } + $shopnum++; + $orderInfo .= "(" . $shopnum . ")" .$v5['shopname'] . '
'; + $shopname = $v5['shopname']; + } + $name = $v5['name']; + if(!empty($v5['spec'])) { + $name .= "(规格:". $v5['spec'].")"; + }elseif (!empty($v5['good_unit'])){ + $name .= "(规格:". $v5['good_unit'].")"; + } + $price = $v5['money']; + $num = $v5['number']; + $prices = sprintf("%.2f",$v5['money']*$v5['number']); + $kw3 = ''; + $kw1 = ''; + $kw2 = ''; + $kw4 = ''; + $str = $name; + $blankNum = $A;//名称控制为14个字节 + $lan = mb_strlen($str,'utf-8'); + $m = 0; + $j=1; + $blankNum++; + $result = array(); + if(strlen($price) < $B){ + $k1 = $B - strlen($price); + for($q=0;$q<$k1;$q++){ + $kw1 .= ' '; + } + $price = $kw1.$price; + } + if(strlen($num) < $C){ + $k2 = $C - strlen($num); + for($q=0;$q<$k2;$q++){ + $kw2 .= ' '; + } + $num = $kw2.$num; + } + if(strlen($prices) < $D){ + $k3 = $D - strlen($prices); + for($q=0;$q<$k3;$q++){ + $kw4 .= ' '; + } + $prices = $kw4.$prices; + } + for ($i=0;$i<$lan;$i++){ + $new = mb_substr($str,$m,$j,'utf-8'); + $j++; + if(mb_strwidth($new,'utf-8')<$blankNum) { + if($m+$j>$lan) { + $m = $m+$j; + $tail = $new; + $lenght = iconv("UTF-8", "GBK//IGNORE", $new); + $k = $A - strlen($lenght); + for($q=0;$q<$k;$q++){ + $kw3 .= ' '; + } + if($m==$j){ + $tail .= $kw3.' '.$price.' '.$num.' '.$prices; + }else{ + $tail .= $kw3.'
'; + } + break; + }else{ + $next_new = mb_substr($str,$m,$j,'utf-8'); + if(mb_strwidth($next_new,'utf-8')<$blankNum) continue; + else{ + $m = $i+1; + $result[] = $new; + $j=1; + } + } + } + } + $head = ''; + foreach ($result as $key=>$value) { + if($key < 1){ + $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value); + $v_lenght = strlen($v_lenght); + if($v_lenght == 13) $value = $value." "; + $head .= $value.' '.$price.' '.$num.' '.$prices; + }else{ + $head .= $value.'
'; + } + } + $orderInfo .= $head.$tail; + if(!empty($v5['o_note'])){ + $orderInfo .= '备注:'.$v5['o_note'].'
'; + } + } + // $time = date('Y-m-d H:i:s', time()); + $orderInfo .= '--------------------------------
'; + if ($arr[0]['box_money'] > 0) { + $kw5 = ''; + $len = 24 - strlen($arr[0]['box_money']); + for ($q = 0; $q < $len; $q++) { + $kw5 .= ' '; + } + $orderInfo .= '包装费:' . $kw5 . $arr[0]['box_money'] . '
'; + } + if($arr[0]['dada_fee'] > 0){ + $kw5 = ''; + $len = 24 - strlen($arr[0]['dada_fee']); + for ($q = 0; $q < $len; $q++) { + $kw5 .= ' '; + } + $orderInfo .= '配送费:'.$kw5.$arr[0]['dada_fee'].'
'; + } + if($arr[0]['yhq_money2'] > 0){ + $yhq_money2 = sprintf("%.2f",$arr[0]['yhq_money2']); + $kw6 = ''; + $len = 25 - strlen($yhq_money2); + for ($q = 0; $q < $len; $q++) { + $kw6 .= ' '; + } + $orderInfo .= '红包:'.$kw6.'-'.$yhq_money2.'
'; + } + $total = '合计:'.$arr[0]['m_money']; + $user_name = $arr[0]['user_name']; + if(strlen($user_name)>18){ + $user_name=substr($user_name,0,18).'...'; + } + $str = $user_name . $total; + $kw5 = ''; + $lenght = iconv("UTF-8", "GBK//IGNORE", $str); + $total_len = 32 - strlen($lenght); + for ($q = 0; $q < $total_len; $q++) { + $kw5 .= ' '; + } + $total_str = $user_name.$kw5.$total; + $orderInfo .= $total_str.'
'; + $orderInfo .= '送货地点:' . $arr[0]['address'] . '
'; + $tel = substr_replace( $arr[0]['tel'], '****', 3, 4); + $orderInfo .= '联系电话:' . $tel . '
'; + $orderInfo .= '配送时间:' . $arr[0]['ps_time'] . '
'; + if(!empty($arr[0]['note'])){ + $orderInfo .= '备注:'.$arr[0]['note'].'

'; + } + //$orderInfo .= 'http://www.feieyun.com';//把解析后的二维码生成的字符串用标签套上即可自动生成二维码 + return $orderInfo; + } +} \ No newline at end of file diff --git a/app/Service/FeiePrintServiceInterface.php b/app/Service/FeiePrintServiceInterface.php new file mode 100644 index 0000000..5e67cdc --- /dev/null +++ b/app/Service/FeiePrintServiceInterface.php @@ -0,0 +1,10 @@ + '微信支付', '2' => '余额支付', '3' => '积分支付', '4' => '货到付款']; + $address_store = $order['address'] . ';' .$order['name']. ';'. substr_replace($order['tel'],'****',3,4); + $address = $order['address'] . ';' .$order['name']. ';'. $order['tel']; + + // 查询子订单,用于发消息给商户 + $order_children = Order::query()->select(['id', 'order_num', 'store_id', 'money', 'time']) + ->where(['order_main_id' => $order_main_id]) + ->get() + ->toArray(); + + $goods_temp_all = []; + foreach ($order_children as $key => &$item) { + + $item = (array)$item; + + // 订单商品 + $order_goods = OrderGoods::query()->select(['name', 'number', 'spec', 'good_unit']) + ->where(['order_id' => $item['id']]) + ->get() + ->toArray(); + + $goods_temp = []; + foreach ($order_goods as $k => &$goods) { + array_push($goods_temp, $goods['name']."*".$goods['number']."/".($goods['spec']?:$goods['good_unit'])); + array_push($goods_temp_all, $goods['name']."*".$goods['number']."/".($goods['spec']?:$goods['good_unit'])); + } + + // 商户/门店的openid + $store = Store::query()->select(['id', 'name']) + ->where(['id' => $item['store_id']]) + ->first()->toArray(); + $store['openid'] = Users::query() + ->where(['id' => $store['user_id']]) + ->value('openid'); + + // 模板数据 + $data_store = [ + 'first' => ['您有新的外卖订单!订单编号:'.$item['order_num'], '#ff0000'], + 'keyword' => [ + ["您的外卖订单详情:\r\n".implode(";\r\n",$goods_temp), '#ff0000'], + $item['money'], + $payTypes[$order['pay_type']], + $item['time']?:'', + $address_store, + ], + 'remark' => [$order['note'], '#4e6ef2'] + ]; + + $ret_store = $this->sendTempMsg($store['openid'], '-M7DG_ACwJxqdAvyvJuAnPpx4xaLf3VkkN0fckno71c',$data_store); + } + + // 模板数据发送消息给用户 + $data_user = [ + 'first' => '您好,下单成功!订单编号:'.$order['order_num'], + 'keyword' => [ + implode(";\r\n", $goods_temp_all), + $order['money'], + $payTypes[$order['pay_type']], + date('Y-m-d H:i:s', $order['time_add']), + $address, + ], + 'remark' => '感谢您的光临,欢迎下次再来!' + ]; + + // 获取用户openid,发送给用户 + $user_openid = Users::query()->where(['id' => $order['user_id']])->value('openid'); + $ret_user = $this->sendTempMsg($user_openid,'-M7DG_ACwJxqdAvyvJuAnPpx4xaLf3VkkN0fckno71c', $data_user); + + } + + public function sendTempMsg($openid, $template_id, $data, $redirect_url = '', $applet_config = ['appid' => '', 'pagepath' => '']) + { + // 先拼个基础的 + $template = [ + 'touser' => $openid, + 'mp_template_msg' => [ + 'appid' => env('OFFICIAL_APP_ID'), + 'template_id' => $template_id, + 'url' => $redirect_url, + ] + ]; + + // 看看有没有小程序跳转的要求 + if ( is_array($applet_config)&&!empty($applet_config)&&!empty($applet_config['appid']) ) { + $template['mp_template_msg']['miniprogram'] = $applet_config; + } + + // 重点来了,拼接关键数据data + if (!is_array($data)) { # 数组都不是,请回去 + return false; + } + + if (is_array($data['first'])) { + $template['mp_template_msg']['data']['first']['value'] = $data['first'][0] ?? ''; + $template['mp_template_msg']['data']['first']['color'] = $data['first'][1] ?? ''; + } else { + $template['mp_template_msg']['data']['first']['value'] = $data['first']; + } + + if (isset($data['keyword'])&&is_array($data['keyword'])) { + foreach ($data['keyword'] as $key => &$keyword) { + $index = $key+1; + + if (is_array($keyword)) { + $template['mp_template_msg']['data']['keyword'.$index]['value'] = $keyword[0] ?? ''; + $template['mp_template_msg']['data']['keyword'.$index]['color'] = $keyword[1] ?? ''; + } else { + $template['mp_template_msg']['data']['keyword'.$index]['value'] = $keyword; + } + + } + } + + if (is_array($data['remark'])) { + $template['mp_template_msg']['data']['remark']['value'] = $data['remark'][0] ?? ''; + $template['mp_template_msg']['data']['remark']['color'] = $data['remark'][1] ?? ''; + } else { + $template['mp_template_msg']['data']['remark']['value'] = $data['remark']; + } + + $app = Factory::miniProgram(config('wxtempmsg')); + $app->uniform_message->send($template); + } + +} \ No newline at end of file diff --git a/app/Service/MiniprogramServiceInterface.php b/app/Service/MiniprogramServiceInterface.php new file mode 100644 index 0000000..b1ebe72 --- /dev/null +++ b/app/Service/MiniprogramServiceInterface.php @@ -0,0 +1,9 @@ + '', 'pagepath' => '']); +} \ No newline at end of file diff --git a/app/Service/MqttServiceInterface.php b/app/Service/MqttServiceInterface.php new file mode 100644 index 0000000..203b908 --- /dev/null +++ b/app/Service/MqttServiceInterface.php @@ -0,0 +1,21 @@ +select(['id','order_num','money', 'pay_type', 'store_id', 'type']); + if ($isMain) { + $orders = $orders->where(['order_main_id' => $orderId])->get()->toArray(); + } else { + $orders = $orders->where(['id' => $orderId])->get()->toArray(); + } + + if(empty($orders)) return; + + // 循环发送 + foreach ($orders as $k => &$order) { + $order['template'] = "懒族生活支付到账".floatval($order['money'])."元"; + // 获取终端ID + $order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei'); + // 发布订阅消息 + $this->pubToMqtt($order['template'], self::TOPIC, $order['to_client_id']); + } + } + + /** + * @inheritDoc + */ + public function pubToMqtt($message, $topic, $toClientId) + { + $task = ApplicationContext::getContainer()->get(MQTTClientTask::class); + $task->publish($message, $topic, $toClientId); + } +} \ No newline at end of file diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 54468a9..2efb470 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -22,7 +22,7 @@ class OrderService implements OrderServiceInterface /** * @Inject - * @var CoupnoServiceInterface + * @var CouponServiceInterface */ protected $couponService; @@ -349,9 +349,110 @@ class OrderService implements OrderServiceInterface /** * @inheritDoc */ - public function addOfflineOrder() + public function addOfflineOrder($data) { - // TODO: Implement addOfflineOrder() method. + Db::beginTransaction(); + try { + // 主订单数据 + $dataMain = []; + + // 获取分布式全局ID + $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class); + $globalRrderId = $generator->generate(); + + // 主订单插入数据 + $currentTime = time(); + $dataMain = [ + 'delivery_no' => '', + 'dada_fee' => 0, + 'market_id' => 0, + 'box_money' => 0, + 'ps_money' => 0, + 'mj_money' => 0, + 'xyh_money' => 0, + 'yhq_money' => 0, + 'yhq_money2' => 0, + 'zk_money' => 0, + 'tel' => '', + 'name' => '', + 'address' => '', + 'area' => '', + 'lat' => '', + 'lng' => '', + 'note' => '', + 'form_id' => '', + 'form_id2' => '', + 'delivery_time' => '', + 'order_type' => 0, + 'coupon_id' => 0, + 'coupon_id2' => 0, + 'store_list' => '', + 'receive_coupon_ids' => '', + 'type' => OrderMain::ORDER_TYPE_OFFLINE, + 'time' => date('Y-m-d H:i:s', $currentTime), + 'time_add' => $currentTime, + 'pay_time' => '', + 'pay_type' => OrderMain::ORDER_PAY_WX, + 'state' => OrderMain::ORDER_STATE_UNPAY, + 'dm_state' => OrderMain::ORDER_STATE_UNPAY, + 'code' => $globalRrderId, + 'jj_note' => '', + 'uniacid' => 2, + 'order_num' => 'dm'.date('YmdHis', time()) . rand(1111, 9999), + 'money' => $data['money'], + 'user_id' => $data['user_id'], + 'store_ids' => $data['store_id'], + 'global_order_id' => $globalRrderId, + ]; + + // 主订单模型保存 + $orderMain = OrderMain::create($dataMain); + $orderMainId = $orderMain->id; + + // 子订单模型保存 + $dataChild = [ + 'uniacid' => 1, + 'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999), + 'user_id' => $orderMain->user_id, + 'store_id' => $data['store_id'], + 'order_main_id' => $orderMainId, + 'state' => OrderMain::ORDER_STATE_UNPAY, + 'tel' => $orderMain->tel, + 'name' => $orderMain->name, + 'address' => $orderMain->address, + 'area' => $orderMain->area, + 'time' => date("Y-m-d H:i:s"), + 'note' => '', + 'delivery_time' => $orderMain->delivery_time, + 'type' => $orderMain->type, + 'lat' => $orderMain->lat, + 'lng' => $orderMain->lng, + 'pay_type' => $orderMain->pay_type, + 'order_type' => $orderMain->order_type, + 'money' => 0, + 'box_money' => 0, + 'mj_money' => 0, + 'yhq_money' => 0, + 'yhq_money2' => 0, + 'zk_money' => 0, + 'coupon_id' => 0, + 'coupon_id2' => 0, + 'xyh_money' => 0, + 'time_add' => date("Y-m-d H:i:s"), + 'jj_note' => '', + 'form_id' => '', + 'form_id2' => '', + 'code' => '', + ]; + + $orderChildId = Order::query()->insertGetId($dataChild); + + Db::commit(); + return $orderMainId; + } catch (Exception $e) { + Db::rollBack(); + return '购买失败'; + } } diff --git a/app/Service/OrderServiceInterface.php b/app/Service/OrderServiceInterface.php index 08ee815..0d5e0a2 100644 --- a/app/Service/OrderServiceInterface.php +++ b/app/Service/OrderServiceInterface.php @@ -17,7 +17,7 @@ interface OrderServiceInterface * 扫码支付 * @return mixed */ - public function addOfflineOrder(); + public function addOfflineOrder($data); /** * 订单是否已经存在 diff --git a/app/TaskWorker/MQTTClientTask.php b/app/TaskWorker/MQTTClientTask.php index 6119690..f751cdc 100644 --- a/app/TaskWorker/MQTTClientTask.php +++ b/app/TaskWorker/MQTTClientTask.php @@ -12,8 +12,46 @@ class MQTTClientTask /** * @Task + * @param string|number $message 消息内容 + * @param string $topic 发布消息到主题,主题名 + * @param string $type 消息类型,cash或tts + * @param string $payId 支付方式,如“支付宝”、“微信”等 + * @param string $toClientId 终端id,如IMEI码 + * @param string $curClientId 当前客户端id */ - public function getClient() + public function publish( + $message, + $topic, + $toClientId = '', + $type = '', + $payId = '', + $curClientId = '' + ) { + $this->getClient(); + + $msgArr = []; + if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) { + $msgArr['cash'] = $message; + $payId AND $msgArr['payid'] = $payId; + } else { + $msgArr['message'] = $message; + } + + if (!empty($toClientId)) { + $topic .= '/'.$toClientId; + } + + $curClientId OR $curClientId = rand(1,999999999); + $success = $this->mqttClient->sendConnect($curClientId); + + if ($success) { + $this->mqttClient->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2); + $this->mqttClient->sendDisconnect(); + } + $this->mqttClient->close(); + } + + protected function getClient() { $this->mqttClient = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT')); $this->mqttClient->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS')); diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 411bb9f..1557ca3 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -9,13 +9,16 @@ declare(strict_types=1); * @contact group@hyperf.io * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ + return [ \App\Service\ServiceEvaluateServiceInterface::class => \App\Service\ServiceEvaluateService::class, \App\Service\AttachmentServiceInterface::class => \App\Service\AttachmentService::class, \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, - \App\Service\DeviceServiceInterFace::class =>\App\Service\DeviceServiceImp::class, + \App\Service\DeviceServiceInterface::class =>\App\Service\DeviceServiceImp::class, \App\Commons\Log::class => \App\Commons\Log::class, \App\Service\IOTServiceInterface::class => \App\Service\IOTAliService::class, \App\Service\OrderServiceInterface::class => \App\Service\OrderService::class, - \App\Service\CoupnoServiceInterface::class => \App\Service\CouponService::class, + \App\Service\CouponServiceInterface::class => \App\Service\CouponService::class, + \App\Service\MqttServiceInterface::class => \App\Service\MqttSpeakerService::class, + \App\Service\FeiePrintServiceInterface::class => \App\Service\FeiePrintService::class, ]; diff --git a/config/config.php b/config/config.php index 7e8d490..ba75ad6 100644 --- a/config/config.php +++ b/config/config.php @@ -36,6 +36,9 @@ return [ 'cert_path' => env('CERT_PATH',''), 'key_path' => env('KEY_PATH',''), 'notify_url' => env('NOTIFY_URL',''), + ], + 'wxtempmsg' => [ + 'app_id' => env('APP_ID',''), + 'secret' => env('APP_SECRET',''), ] - ]; diff --git a/config/routes.php b/config/routes.php index 266122f..7902ff0 100644 --- a/config/routes.php +++ b/config/routes.php @@ -39,6 +39,7 @@ Router::addGroup('/v1/',function (){ //订单相关 Router::post('Order/addOnline', 'App\Controller\OrderController@addOnlineOrder'); + Router::post('Order/addOffline', 'App\Controller\OrderController@addOfflineOrder'); //小程序支付相关 Router::post('wxminipay/online', 'App\Controller\PaymentController@wxminiPayOnline'); From 4e675fd7580b27288cde34f34ac6cde89e9c1e74 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 21:50:22 +0800 Subject: [PATCH 122/172] =?UTF-8?q?=E4=BF=AE=E6=94=B9API=20AUTH=E4=B8=AD?= =?UTF-8?q?=E9=97=B4=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 4 ++-- config/autoload/middlewares.php | 4 ++-- config/routes.php | 5 ++++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index 5047f27..9fc92ae 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -35,7 +35,7 @@ class PaymentController extends BaseController 'out_trade_no' => $orderMain->global_order_id, // 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), 'total_fee' => 1, - 'notify_url' => config('site_host') . '/v1/notify/wxminionline', + 'notify_url' => config('site_host') . '/wechat/notify/wxminionline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); @@ -75,7 +75,7 @@ class PaymentController extends BaseController 'body' => '懒族生活 - 当面支付', 'out_trade_no' => $orderMain->global_order_id, 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), - 'notify_url' => config('site_host') . '/v1/notify/wxminioffline', + 'notify_url' => config('site_host') . '/wechat/notify/wxminioffline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index 5eb19a5..fa4a0fc 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -11,8 +11,8 @@ declare(strict_types=1); */ return [ 'http' => [ - \App\Middleware\Auth\ApiMiddleware::class, - \Hyperf\Validation\Middleware\ValidationMiddleware::class, + // \App\Middleware\Auth\ApiMiddleware::class, \App\Middleware\CorsMiddleware::class, + \Hyperf\Validation\Middleware\ValidationMiddleware::class, ], ]; diff --git a/config/routes.php b/config/routes.php index 7902ff0..ab8a2ed 100644 --- a/config/routes.php +++ b/config/routes.php @@ -44,7 +44,10 @@ Router::addGroup('/v1/',function (){ //小程序支付相关 Router::post('wxminipay/online', 'App\Controller\PaymentController@wxminiPayOnline'); Router::post('wxminipay/offline', 'App\Controller\PaymentController@wxminiPayOffline'); + +},['middleware' => [\App\Middleware\Auth\ApiMiddleware::class]]); + +Router::addGroup('/wechat/',function () { Router::post('notify/wxminionline', 'App\Controller\NotifyController@wxminiOnline'); Router::post('notify/wxminioffline', 'App\Controller\NotifyController@wxminiOffline'); - }); \ No newline at end of file From f6dab71db5cdda9c5b5a3181a7a6ee1b03393f5e Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 22:26:13 +0800 Subject: [PATCH 123/172] =?UTF-8?q?easywechat=E7=BB=91=E5=AE=9A=E6=96=B0re?= =?UTF-8?q?quest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 17 ++++++++++++++--- app/Model/Goods.php | 2 ++ app/Model/Order.php | 1 + app/Model/OrderGoods.php | 1 + app/Model/OrderSalesStatistic.php | 2 ++ app/Model/SpecCombination.php | 1 + app/Model/SystemConfig.php | 1 + app/Model/Users.php | 1 + 8 files changed, 23 insertions(+), 3 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 3ac5cd3..80f8b0f 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -20,6 +20,7 @@ use Hyperf\DbConnection\Db; use Hyperf\Guzzle\CoroutineHandler; use Exception; use Hyperf\Di\Annotation\Inject; +use Symfony\Component\HttpFoundation\Request; class NotifyController extends BaseController { @@ -54,6 +55,16 @@ class NotifyController extends BaseController $config = config('wxpay'); $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; + + $get = $this->request->getQueryParams(); + $post = $this->request->getParsedBody(); + $cookie = $this->request->getCookieParams(); + $files = $this->request->getUploadedFiles(); + $server = $this->request->getServerParams(); + $xml = $this->request->getBody()->getContents(); + + $app['request'] = new Request($get,$post,[],$cookie,$files,$server,$xml); + var_dump('inside'); // 通知回调,进行业务处理 Db::beginTransaction(); @@ -109,9 +120,7 @@ class NotifyController extends BaseController } } - - - // return true; + return true; } // 修改订单、子订单状态 @@ -188,6 +197,8 @@ class NotifyController extends BaseController $res = $this->feiePrintService->feiePrint($orderMain->order_num); var_dump($res); + return true; + }); var_dump('$response', $response); diff --git a/app/Model/Goods.php b/app/Model/Goods.php index 83f2304..8009bda 100644 --- a/app/Model/Goods.php +++ b/app/Model/Goods.php @@ -9,4 +9,6 @@ class Goods extends Model const INVENTORY_NOLIMIT = 1; protected $table = 'ims_cjdc_goods'; + public $timestamps = false; + } \ No newline at end of file diff --git a/app/Model/Order.php b/app/Model/Order.php index 535bbc7..7053f71 100644 --- a/app/Model/Order.php +++ b/app/Model/Order.php @@ -7,5 +7,6 @@ namespace App\Model; class Order extends Model { protected $table = 'ims_cjdc_order'; + public $timestamps = false; } \ No newline at end of file diff --git a/app/Model/OrderGoods.php b/app/Model/OrderGoods.php index 12b1702..c82b527 100644 --- a/app/Model/OrderGoods.php +++ b/app/Model/OrderGoods.php @@ -5,4 +5,5 @@ namespace App\Model; class OrderGoods extends Model { protected $table = 'ims_cjdc_order_goods'; + public $timestamps = false; } \ No newline at end of file diff --git a/app/Model/OrderSalesStatistic.php b/app/Model/OrderSalesStatistic.php index a20edf8..5b58f92 100644 --- a/app/Model/OrderSalesStatistic.php +++ b/app/Model/OrderSalesStatistic.php @@ -26,4 +26,6 @@ class OrderSalesStatistic extends Model * @var array */ protected $casts = []; + + public $timestamps = false; } \ No newline at end of file diff --git a/app/Model/SpecCombination.php b/app/Model/SpecCombination.php index adf23a3..9d112d0 100644 --- a/app/Model/SpecCombination.php +++ b/app/Model/SpecCombination.php @@ -8,6 +8,7 @@ class SpecCombination extends Model { protected $table = 'ims_cjdc_spec_combination'; + public $timestamps = false; public function goods() { diff --git a/app/Model/SystemConfig.php b/app/Model/SystemConfig.php index 5f81111..74e8bb8 100644 --- a/app/Model/SystemConfig.php +++ b/app/Model/SystemConfig.php @@ -7,4 +7,5 @@ namespace App\Model; class SystemConfig extends Model { protected $table = 'ims_cjdc_system_config'; + public $timestamps = false; } \ No newline at end of file diff --git a/app/Model/Users.php b/app/Model/Users.php index 2a8d910..32cff4d 100644 --- a/app/Model/Users.php +++ b/app/Model/Users.php @@ -5,4 +5,5 @@ namespace App\Model; class Users extends Model { protected $table = 'ims_cjdc_user'; + public $timestamps = false; } \ No newline at end of file From 488f4666b0e4eb196264ad9748e2726d281b3e6b Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:00:43 +0800 Subject: [PATCH 124/172] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E7=9A=84=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 18 +++++++++--------- app/Model/OrderMain.php | 1 + app/Service/OrderService.php | 7 ++++--- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 80f8b0f..f54b3fc 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -136,11 +136,11 @@ class NotifyController extends BaseController // 更新商户销量 $upStoreScore = Store::query() - ->whereIn('id', $orderMain->order_ids) + ->whereIn('id', explode(',', $orderMain->store_ids)) ->update(['score' => Db::raw('score+1')]); // 更新商品库存和销量 - $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'createtime']) + $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id']) ->where(['order_main_id' => $orderMain->id]) ->get() ->toArray(); @@ -153,7 +153,7 @@ class NotifyController extends BaseController $goods = Goods::find($goodsItem['id']); // 库存处理,有规格 - if ($goodsItem->combination_id) { + if ($goodsItem['combination_id']) { $combination = SpecCombination::find($goodsItem['combination_id']); $combination->number = $combination->number - $goodsItem['number']; $combination->save(); @@ -168,14 +168,14 @@ class NotifyController extends BaseController // 月销流水 $statistics = []; - foreach ($orders as $key => & $order) { + foreach ($orders as $key => &$order) { $statistics[] = [ - 'money' => $order->money, - 'user_id' => $order->user_id, - 'store_id' => $order->store_id, + 'money' => $order['money'], + 'user_id' => $order['user_id'], + 'store_id' => $order['store_id'], 'market_id' => $orderMain->market_id, - 'order_id' => $order->id, - 'createtime' => strtotime($order->pay_time), + 'order_id' => $order['id'], + 'createtime' => strtotime($order['pay_time']), ]; } diff --git a/app/Model/OrderMain.php b/app/Model/OrderMain.php index 4972484..92213ad 100644 --- a/app/Model/OrderMain.php +++ b/app/Model/OrderMain.php @@ -81,6 +81,7 @@ class OrderMain extends Model 'pay_time', 'jj_note', 'global_order_id', + 'store_ids', ]; } \ No newline at end of file diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 2efb470..decf5ab 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -36,10 +36,11 @@ class OrderService implements OrderServiceInterface // 订单判重 $dataMain = $data; + var_dump($dataMain); if ($orderMainId = $this->existsByOrderNum($data['order_num'])) { return $orderMainId; } - + var_dump($orderMainId); Db::beginTransaction(); try { @@ -62,12 +63,12 @@ class OrderService implements OrderServiceInterface Db::rollBack(); return '订单中商品不存在或已失效'; } - +var_dump('storelist', $storeList); // 获取商户IDs foreach ($storeList as &$item) { $dataMain['store_ids'] .= empty($dataMain['store_ids']) ? $item['store_id'] : ','.$item['store_id']; } - + var_dump('$dataMain[\'store_ids\']', $dataMain['store_ids']); // 主订单插入数据 $currentTime = time(); $dataMain['time'] = date('Y-m-d H:i:s', $currentTime); From cc3b2eb74927b53e09268edf2e3635789a8ea99a Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:05:26 +0800 Subject: [PATCH 125/172] Fix --- app/Controller/NotifyController.php | 2 +- app/Service/MqttSpeakerService.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index f54b3fc..074cf53 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -140,7 +140,7 @@ class NotifyController extends BaseController ->update(['score' => Db::raw('score+1')]); // 更新商品库存和销量 - $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id']) + $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'pay_time']) ->where(['order_main_id' => $orderMain->id]) ->get() ->toArray(); diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index 9724497..5a8b802 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -5,6 +5,7 @@ namespace App\Service; use App\Model\Order; use App\Model\Store; use App\TaskWorker\MQTTClientTask; +use Hyperf\Utils\ApplicationContext; class MqttSpeakerService implements MqttServiceInterface { From d46f86f6a41b303f3e664741ad3f8511fba98c1b Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:07:53 +0800 Subject: [PATCH 126/172] Fix --- app/Service/MiniprogramService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/MiniprogramService.php b/app/Service/MiniprogramService.php index e977403..ab74ec4 100644 --- a/app/Service/MiniprogramService.php +++ b/app/Service/MiniprogramService.php @@ -48,7 +48,7 @@ class MiniprogramService implements MiniprogramServiceInterface } // 商户/门店的openid - $store = Store::query()->select(['id', 'name']) + $store = Store::query()->select(['id', 'name', 'user_id']) ->where(['id' => $item['store_id']]) ->first()->toArray(); $store['openid'] = Users::query() From 9b76889dcbc35c954e9e1974a07e491aed346eb9 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:16:14 +0800 Subject: [PATCH 127/172] Fix --- app/Controller/NotifyController.php | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 074cf53..5eeb3bc 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -67,10 +67,9 @@ class NotifyController extends BaseController var_dump('inside'); // 通知回调,进行业务处理 - Db::beginTransaction(); - try { - $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - + $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { + Db::beginTransaction(); + try { var_dump('message', $message); // 支付失败或者通知失败 if ( @@ -197,20 +196,19 @@ class NotifyController extends BaseController $res = $this->feiePrintService->feiePrint($orderMain->order_num); var_dump($res); + Db::commit(); return true; - }); - - var_dump('$response', $response); - Db::rollBack(); - $response->send(); + } catch (Exception $e) { - } catch (\EasyWeChat\Kernel\Exceptions\Exception $e) { + var_dump($e->getMessage()); + Db::rollBack(); + $fail('Exception'); + } - var_dump($e->getMessage()); - Db::rollBack(); + }); - } + $response->send(); } From 1eef42fab02754ddee5eec0e1d55f0d752c1dcc4 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:24:29 +0800 Subject: [PATCH 128/172] FIX --- app/Service/MiniprogramService.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/Service/MiniprogramService.php b/app/Service/MiniprogramService.php index ab74ec4..93bc586 100644 --- a/app/Service/MiniprogramService.php +++ b/app/Service/MiniprogramService.php @@ -10,6 +10,7 @@ use App\Model\OrderMain; use App\Model\Store; use App\Model\Users; use EasyWeChat\Factory; +use Hyperf\Guzzle\CoroutineHandler; class MiniprogramService implements MiniprogramServiceInterface { @@ -141,6 +142,7 @@ class MiniprogramService implements MiniprogramServiceInterface } $app = Factory::miniProgram(config('wxtempmsg')); + $app['guzzle_handler'] = CoroutineHandler::class; $app->uniform_message->send($template); } From 5587e759aa3123bfe851205d0af08db1c923352d Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:40:21 +0800 Subject: [PATCH 129/172] f --- app/Controller/NotifyController.php | 26 ++++---------------------- 1 file changed, 4 insertions(+), 22 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 5eeb3bc..d22e6da 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -82,6 +82,7 @@ class NotifyController extends BaseController LogLabel::PAY_NOTIFY_WXMINI, $message ); + Db::rollBack(); $fail('Unknown error but FAIL'); } @@ -89,36 +90,17 @@ class NotifyController extends BaseController $orderMain = OrderMain::query() ->where([ 'global_order_id' => $message['out_trade_no'], - 'type' => OrderMain::ORDER_TYPE_ONLINE, - 'state' => OrderMain::ORDER_STATE_UNPAY + 'type' => OrderMain::ORDER_TYPE_ONLINE ]) - ->where('time', '>=', date('Y-m-d H:i:s', (time() - 900))) ->first(); var_dump('$orderMain', $orderMain); // 订单不存在 if (empty($orderMain)) { - $this->log->event( LogLabel::PAY_NOTIFY_WXMINI, - $orderMain + ['global_order_id_fail' => $message['out_trade_no']] ); - - // 去查一下微信订单,只处理未支付的情况 TODO 其他情况处理 - $wxOrder = $app->order->queryByOutTradeNumber($message['out_trade_no']); - // 查询成功 - if ($wxOrder['return_code'] == 'SUCCESS') { - if ($wxOrder['result_code'] == 'SUCCESS') { - // 看订单支付状态,处理未支付的情况,把订单处理成未支付 - if ($wxOrder['trade_state'] != 'NOTPAY') { - OrderMain::query() - ->where(['global_order_id' => $message['out_trade_no']]) - ->update(['state' => OrderMain::ORDER_STATE_UNPAY]); - - $fail('Order not paid'); - } - } - } - + Db::rollBack(); return true; } From c208d602986d8a791896af2b8fcf42f704dbd206 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:43:13 +0800 Subject: [PATCH 130/172] Fix --- app/Controller/NotifyController.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index d22e6da..ba9a1e8 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -166,17 +166,17 @@ class NotifyController extends BaseController // 喇叭通知,兼容旧音响,MQTT+IOT $res = $this->mqttSpeakerService->speakToStore($orderMain->id); - var_dump($res); + var_dump('speakToStore',$res); $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); - var_dump($res); + var_dump('pubMsgToStoreByOrderMainId',$res); // 公众号模板消息 - $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); - var_dump($res); + // $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); + // var_dump('sendTemMsgForOnlineOrder',$res); // 打印订单,自动打印 TODO 后续优化调用逻辑 $res = $this->feiePrintService->feiePrint($orderMain->order_num); - var_dump($res); + var_dump('feiePrint',$res); Db::commit(); return true; From d19d49995beda68cb3d539486bcaac54839e080c Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:46:36 +0800 Subject: [PATCH 131/172] Fix --- app/Service/FeiePrintService.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/Service/FeiePrintService.php b/app/Service/FeiePrintService.php index b822175..7bfb6f1 100644 --- a/app/Service/FeiePrintService.php +++ b/app/Service/FeiePrintService.php @@ -31,9 +31,10 @@ class FeiePrintService implements FeiePrintServiceInterface ->join('ims_cjdc_feprint as f','m.market_id','=', 'f.market_id','inner') ->join('ims_cjdc_store as s','s.id','=', 'o.store_id','inner') ->where('m.order_num', $order_num) - ->select("o.note as o_note,g.name,g.number,g.money,g.good_unit,m.delivery_time as ps_time,m.address,m.note,m.name as user_name,m.dada_fee,m.money as m_money,m.yhq_money2,m.box_money,f.sn,m.tel,m.order_num,g.id,g.spec,s.name as shopname") - ->order('s.id') - ->get(); + ->selectRaw("o.note as o_note,g.name,g.number,g.money,g.good_unit,m.delivery_time as ps_time,m.address,m.note,m.name as user_name,m.dada_fee,m.money as m_money,m.yhq_money2,m.box_money,f.sn,m.tel,m.order_num,g.id,g.spec,s.name as shopname") + ->orderBy('s.id') + ->get() + ->toArray(); $content = $this->printFormat($data, 14, 6, 3, 6); $res = $this->printMsg($data[0]['sn'], $content, 1); From bbeebb64a90fe57956c94c43e6703d3b61265953 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 00:05:47 +0800 Subject: [PATCH 132/172] F --- app/Service/FeiePrintService.php | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/app/Service/FeiePrintService.php b/app/Service/FeiePrintService.php index 7bfb6f1..0b1f1aa 100644 --- a/app/Service/FeiePrintService.php +++ b/app/Service/FeiePrintService.php @@ -3,6 +3,7 @@ namespace App\Service; use App\Libs\FeiePrintClient; +use App\Model\OrderMain; use Hyperf\DbConnection\Db; use Hyperf\Utils\ApplicationContext; @@ -25,16 +26,20 @@ class FeiePrintService implements FeiePrintServiceInterface public function feiePrint($order_num) { + // TODO 对象数组=》二维数组 $data = Db::table('ims_cjdc_order_main as m') ->join('ims_cjdc_order as o','o.order_main_id', '=', 'm.id','inner') ->join('ims_cjdc_order_goods as g','o.id','=', 'g.order_id','inner') ->join('ims_cjdc_feprint as f','m.market_id','=', 'f.market_id','inner') ->join('ims_cjdc_store as s','s.id','=', 'o.store_id','inner') - ->where('m.order_num', $order_num) + ->where('m.global_order_id', $order_num) ->selectRaw("o.note as o_note,g.name,g.number,g.money,g.good_unit,m.delivery_time as ps_time,m.address,m.note,m.name as user_name,m.dada_fee,m.money as m_money,m.yhq_money2,m.box_money,f.sn,m.tel,m.order_num,g.id,g.spec,s.name as shopname") ->orderBy('s.id') ->get() ->toArray(); + foreach ($data as $key => &$item) { + $item = (array)$item; + } $content = $this->printFormat($data, 14, 6, 3, 6); $res = $this->printMsg($data[0]['sn'], $content, 1); @@ -135,8 +140,8 @@ class FeiePrintService implements FeiePrintServiceInterface if($m+$j>$lan) { $m = $m+$j; $tail = $new; - $lenght = iconv("UTF-8", "GBK//IGNORE", $new); - $k = $A - strlen($lenght); + // $lenght = iconv("UTF-8", "GBK//IGNORE", $new); + $k = $A - mb_strlen($new); for($q=0;$q<$k;$q++){ $kw3 .= ' '; } @@ -160,8 +165,8 @@ class FeiePrintService implements FeiePrintServiceInterface $head = ''; foreach ($result as $key=>$value) { if($key < 1){ - $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value); - $v_lenght = strlen($v_lenght); + // $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value); + $v_lenght = mb_strlen($value); if($v_lenght == 13) $value = $value." "; $head .= $value.' '.$price.' '.$num.' '.$prices; }else{ @@ -207,8 +212,8 @@ class FeiePrintService implements FeiePrintServiceInterface } $str = $user_name . $total; $kw5 = ''; - $lenght = iconv("UTF-8", "GBK//IGNORE", $str); - $total_len = 32 - strlen($lenght); + // $lenght = iconv("UTF-8", "GBK//IGNORE", $str); + $total_len = 32 - mb_strlen($str); for ($q = 0; $q < $total_len; $q++) { $kw5 .= ' '; } From ec8740fe1b709d8327eb5afb0a23cce739da6155 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 00:13:17 +0800 Subject: [PATCH 133/172] Fix --- app/Controller/NotifyController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index ba9a1e8..9d7fa85 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -175,7 +175,7 @@ class NotifyController extends BaseController // var_dump('sendTemMsgForOnlineOrder',$res); // 打印订单,自动打印 TODO 后续优化调用逻辑 - $res = $this->feiePrintService->feiePrint($orderMain->order_num); + $res = $this->feiePrintService->feiePrint($orderMain->global_order_id); var_dump('feiePrint',$res); Db::commit(); From 49383d9ab56f293dde9ea7199e79a4227da5c69c Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 00:29:15 +0800 Subject: [PATCH 134/172] F --- app/Controller/NotifyController.php | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 9d7fa85..6f9a494 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -20,6 +20,7 @@ use Hyperf\DbConnection\Db; use Hyperf\Guzzle\CoroutineHandler; use Exception; use Hyperf\Di\Annotation\Inject; +use Hyperf\HttpMessage\Stream\SwooleStream; use Symfony\Component\HttpFoundation\Request; class NotifyController extends BaseController @@ -65,12 +66,10 @@ class NotifyController extends BaseController $app['request'] = new Request($get,$post,[],$cookie,$files,$server,$xml); - var_dump('inside'); // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { Db::beginTransaction(); try { - var_dump('message', $message); // 支付失败或者通知失败 if ( empty($message) @@ -93,7 +92,7 @@ class NotifyController extends BaseController 'type' => OrderMain::ORDER_TYPE_ONLINE ]) ->first(); - var_dump('$orderMain', $orderMain); + // 订单不存在 if (empty($orderMain)) { $this->log->event( @@ -166,31 +165,34 @@ class NotifyController extends BaseController // 喇叭通知,兼容旧音响,MQTT+IOT $res = $this->mqttSpeakerService->speakToStore($orderMain->id); - var_dump('speakToStore',$res); $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); - var_dump('pubMsgToStoreByOrderMainId',$res); // 公众号模板消息 // $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); - // var_dump('sendTemMsgForOnlineOrder',$res); // 打印订单,自动打印 TODO 后续优化调用逻辑 $res = $this->feiePrintService->feiePrint($orderMain->global_order_id); - var_dump('feiePrint',$res); Db::commit(); return true; } catch (Exception $e) { - var_dump($e->getMessage()); + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + ['exception_fail' => $e->getMessage()] + ); Db::rollBack(); $fail('Exception'); } }); - $response->send(); + var_dump('reponse',$response->getContent()); + return $this->response + ->withHeader('Content-Type', 'application/xml') + ->withStatus(200) + ->withBody(new SwooleStream($response->getContent())); } From 4417db873950e5ac2c9f368155d19fb3344dd0f5 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 00:34:12 +0800 Subject: [PATCH 135/172] f --- app/Controller/NotifyController.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 6f9a494..90ced49 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -68,6 +68,8 @@ class NotifyController extends BaseController // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { + + var_dump('message',$message); Db::beginTransaction(); try { // 支付失败或者通知失败 @@ -190,7 +192,7 @@ class NotifyController extends BaseController var_dump('reponse',$response->getContent()); return $this->response - ->withHeader('Content-Type', 'application/xml') + ->withHeader('Content-Type', 'text/xml') ->withStatus(200) ->withBody(new SwooleStream($response->getContent())); From 2d8ed3c41b2855212f64ebf661a1fee2f3dafc33 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 00:54:16 +0800 Subject: [PATCH 136/172] Fx --- app/Controller/NotifyController.php | 4 +--- app/Service/MiniprogramService.php | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 90ced49..633ff04 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -69,7 +69,6 @@ class NotifyController extends BaseController // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - var_dump('message',$message); Db::beginTransaction(); try { // 支付失败或者通知失败 @@ -170,7 +169,7 @@ class NotifyController extends BaseController $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); // 公众号模板消息 - // $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); + $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); // 打印订单,自动打印 TODO 后续优化调用逻辑 $res = $this->feiePrintService->feiePrint($orderMain->global_order_id); @@ -190,7 +189,6 @@ class NotifyController extends BaseController }); - var_dump('reponse',$response->getContent()); return $this->response ->withHeader('Content-Type', 'text/xml') ->withStatus(200) diff --git a/app/Service/MiniprogramService.php b/app/Service/MiniprogramService.php index 93bc586..33a9b4d 100644 --- a/app/Service/MiniprogramService.php +++ b/app/Service/MiniprogramService.php @@ -104,9 +104,7 @@ class MiniprogramService implements MiniprogramServiceInterface ]; // 看看有没有小程序跳转的要求 - if ( is_array($applet_config)&&!empty($applet_config)&&!empty($applet_config['appid']) ) { - $template['mp_template_msg']['miniprogram'] = $applet_config; - } + $template['mp_template_msg']['miniprogram'] = $applet_config; // 重点来了,拼接关键数据data if (!is_array($data)) { # 数组都不是,请回去 From 9820a42affb5e7d07cffd505949d7528bfaa5c21 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 09:30:10 +0800 Subject: [PATCH 137/172] =?UTF-8?q?=E5=96=87=E5=8F=AD=E6=92=AD=E6=8A=A5?= =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Libs/MQTTClient.php | 2 +- app/Service/FeiePrintService.php | 6 +++--- app/TaskWorker/MQTTClientTask.php | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/Libs/MQTTClient.php b/app/Libs/MQTTClient.php index d2a9490..56584c0 100644 --- a/app/Libs/MQTTClient.php +++ b/app/Libs/MQTTClient.php @@ -322,7 +322,7 @@ class MQTTClient { } // Set socket timeout - ini_set('default_socket_timeout', 10); + ini_set('default_socket_timeout', '10'); stream_set_timeout($this->socket, 0, $this->socketTimeout * 1000); // Set stream to non-blocking mode, ie do not wait to read if stream is empty stream_set_blocking($this->socket, true); diff --git a/app/Service/FeiePrintService.php b/app/Service/FeiePrintService.php index 0b1f1aa..0a7365d 100644 --- a/app/Service/FeiePrintService.php +++ b/app/Service/FeiePrintService.php @@ -141,7 +141,7 @@ class FeiePrintService implements FeiePrintServiceInterface $m = $m+$j; $tail = $new; // $lenght = iconv("UTF-8", "GBK//IGNORE", $new); - $k = $A - mb_strlen($new); + $k = $A - mb_strlen($new,'utf-8'); for($q=0;$q<$k;$q++){ $kw3 .= ' '; } @@ -166,7 +166,7 @@ class FeiePrintService implements FeiePrintServiceInterface foreach ($result as $key=>$value) { if($key < 1){ // $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value); - $v_lenght = mb_strlen($value); + $v_lenght = mb_strlen($value,'utf-8'); if($v_lenght == 13) $value = $value." "; $head .= $value.' '.$price.' '.$num.' '.$prices; }else{ @@ -213,7 +213,7 @@ class FeiePrintService implements FeiePrintServiceInterface $str = $user_name . $total; $kw5 = ''; // $lenght = iconv("UTF-8", "GBK//IGNORE", $str); - $total_len = 32 - mb_strlen($str); + $total_len = 32 - mb_strlen($str,'utf-8'); for ($q = 0; $q < $total_len; $q++) { $kw5 .= ' '; } diff --git a/app/TaskWorker/MQTTClientTask.php b/app/TaskWorker/MQTTClientTask.php index f751cdc..e49f562 100644 --- a/app/TaskWorker/MQTTClientTask.php +++ b/app/TaskWorker/MQTTClientTask.php @@ -41,7 +41,7 @@ class MQTTClientTask $topic .= '/'.$toClientId; } - $curClientId OR $curClientId = rand(1,999999999); + $curClientId OR $curClientId = (string)rand(1,999999999); $success = $this->mqttClient->sendConnect($curClientId); if ($success) { From 28861f0494a558ca26a45aac64803e9c74e49bf9 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 09:57:34 +0800 Subject: [PATCH 138/172] =?UTF-8?q?=E5=8E=BB=E9=99=A4=E4=B8=8B=E5=8D=95?= =?UTF-8?q?=E8=B0=83=E8=AF=95=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/OrderService.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index decf5ab..75bca49 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -36,11 +36,11 @@ class OrderService implements OrderServiceInterface // 订单判重 $dataMain = $data; - var_dump($dataMain); + if ($orderMainId = $this->existsByOrderNum($data['order_num'])) { return $orderMainId; } - var_dump($orderMainId); + Db::beginTransaction(); try { @@ -63,12 +63,12 @@ class OrderService implements OrderServiceInterface Db::rollBack(); return '订单中商品不存在或已失效'; } -var_dump('storelist', $storeList); + // 获取商户IDs foreach ($storeList as &$item) { $dataMain['store_ids'] .= empty($dataMain['store_ids']) ? $item['store_id'] : ','.$item['store_id']; } - var_dump('$dataMain[\'store_ids\']', $dataMain['store_ids']); + // 主订单插入数据 $currentTime = time(); $dataMain['time'] = date('Y-m-d H:i:s', $currentTime); From 6abb9f90813a0743483f007244529cb9eee95a1e Mon Sep 17 00:00:00 2001 From: Lemon <15040771@qq.com> Date: Fri, 14 Aug 2020 10:41:04 +0800 Subject: [PATCH 139/172] =?UTF-8?q?=E5=90=88=E8=AE=A1=E9=87=91=E9=A2=9D?= =?UTF-8?q?=E6=8D=A2=E8=A1=8C=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/FeiePrintService.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/Service/FeiePrintService.php b/app/Service/FeiePrintService.php index 0a7365d..9f8f31d 100644 --- a/app/Service/FeiePrintService.php +++ b/app/Service/FeiePrintService.php @@ -141,7 +141,7 @@ class FeiePrintService implements FeiePrintServiceInterface $m = $m+$j; $tail = $new; // $lenght = iconv("UTF-8", "GBK//IGNORE", $new); - $k = $A - mb_strlen($new,'utf-8'); + $k = $A - mb_strwidth($new,'utf-8'); for($q=0;$q<$k;$q++){ $kw3 .= ' '; } @@ -166,7 +166,7 @@ class FeiePrintService implements FeiePrintServiceInterface foreach ($result as $key=>$value) { if($key < 1){ // $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value); - $v_lenght = mb_strlen($value,'utf-8'); + $v_lenght = mb_strwidth($value,'utf-8'); if($v_lenght == 13) $value = $value." "; $head .= $value.' '.$price.' '.$num.' '.$prices; }else{ @@ -213,7 +213,7 @@ class FeiePrintService implements FeiePrintServiceInterface $str = $user_name . $total; $kw5 = ''; // $lenght = iconv("UTF-8", "GBK//IGNORE", $str); - $total_len = 32 - mb_strlen($str,'utf-8'); + $total_len = 32 - mb_strwidth($str,'utf-8'); for ($q = 0; $q < $total_len; $q++) { $kw5 .= ' '; } From e952ee31ead1d2a9e139b2b0c38e51b98ded57e9 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 11:52:30 +0800 Subject: [PATCH 140/172] =?UTF-8?q?=E5=BD=93=E9=9D=A2=E4=BB=98=E6=94=AF?= =?UTF-8?q?=E4=BB=98=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 167 ++++++++++++++++++-- app/Model/StoreAccount.php | 9 ++ app/Service/MiniprogramService.php | 66 +++++++- app/Service/MiniprogramServiceInterface.php | 32 ++++ app/Service/UserService.php | 76 +++++++++ app/Service/UserServiceInterface.php | 28 ++++ 6 files changed, 360 insertions(+), 18 deletions(-) create mode 100644 app/Model/StoreAccount.php create mode 100644 app/Service/UserService.php create mode 100644 app/Service/UserServiceInterface.php diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 633ff04..7d88a32 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -10,11 +10,14 @@ use App\Model\OrderMain; use App\Model\OrderSalesStatistic; use App\Model\SpecCombination; use App\Model\Store; +use App\Model\StoreAccount; use App\Model\SystemConfig; +use App\Model\Users; use App\Service\DeviceServiceInterface; use App\Service\FeiePrintServiceInterface; use App\Service\MiniprogramService; use App\Service\MqttServiceInterface; +use App\Service\UserServiceInterface; use EasyWeChat\Factory; use Hyperf\DbConnection\Db; use Hyperf\Guzzle\CoroutineHandler; @@ -50,6 +53,12 @@ class NotifyController extends BaseController */ protected $feiePrintService; + /** + * @Inject + * @var UserServiceInterface + */ + protected $userService; + public function wxminiOnline() { @@ -202,33 +211,159 @@ class NotifyController extends BaseController $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; + $get = $this->request->getQueryParams(); + $post = $this->request->getParsedBody(); + $cookie = $this->request->getCookieParams(); + $files = $this->request->getUploadedFiles(); + $server = $this->request->getServerParams(); + $xml = $this->request->getBody()->getContents(); + + $app['request'] = new Request($get,$post,[],$cookie,$files,$server,$xml); + // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - $this->log->event( - LogLabel::PAY_NOTIFY_WXMINI, - $message - ); + Db::beginTransaction(); + try { + // 支付失败或者通知失败 + if ( + empty($message) + || $message['return_code'] != 'SUCCESS' + || !isset($message['result_code']) + || $message['result_code'] != 'SUCCESS' + ) { + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $message + ); + Db::rollBack(); + $fail('Unknown error but FAIL'); + } - // 查询订单 - $orderMain = OrderMain::query() - ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_OFFLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) - ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) - ->first(); + // 查询订单 + $orderMain = OrderMain::query() + ->where([ + 'global_order_id' => $message['out_trade_no'], + 'type' => OrderMain::ORDER_TYPE_OFFLINE + ]) + ->first(); - if (empty($orderMain)) { - // 去查一下微信订单 - $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); + // 订单不存在 + if (empty($orderMain)) { + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + ['global_order_id_fail' => $message['out_trade_no']] + ); + Db::rollBack(); + return true; + } + + // 修改订单、子订单状态 + $currentTime = time(); + $orderMain->state = OrderMain::ORDER_STATE_UNTAKE; + $orderMain->dm_state = OrderMain::ORDER_STATE_UNTAKE; + $orderMain->time_pay = $currentTime; + $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime); + $orderMain->save(); + + // 查询子订单,当面付目前实际上只有一个子订单 + $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'pay_time']) + ->where(['order_main_id' => $orderMain->id]) + ->get() + ->toArray(); + + // 商户钱包、流水资金、奖励、发布模板消息处理 + foreach ($orders as $key => $orderItem) { + + $recordBase = [ + 'user_id' => $orderItem['user_id'], + 'order_id' => $orderItem['id'], + 'store_id' => $orderItem['store_id'], + 'type' => 1, + 'time' => date('Y-m-d H:i:s', $currentTime), + 'add_time' => $currentTime, + ]; + + // 钱包 + $store = Store::find($orderItem['store_id']); + $store->store_wallet = bcadd($store->store_wallet, $orderItem['money'], 2); + $store->save(); + + // 流水 + $record = [ + 'money' => $orderItem['money'], + 'note' => '当面付订单收入', + 'category' => 2, + ]; + StoreAccount::query()->insert(array($recordBase, $record)); + + // 平台新用户奖励给商户 + $isStageNewUser = $this->userService->isStageNewUser($orderItem['user_id']); + $needAward = false; + $awardAmount = 0; + if ($isStageNewUser) { + $awardAmount = SystemConfig::query()->where(['type' => 1, 'menu_name' => 'award_new_user'])->value('value'); + // 流水 + $record = [ + 'money' => $awardAmount, + 'note' => '新用户下单成功,平台奖励', + 'category' => 3, + ]; + $needAward = true; + } else { + $isStoreFirstOrderToday = $this->userService->isStoreFirstOrderToday($orderItem['user_id'],$orderItem['store_id'],$orderItem['id']); + if ($isStoreFirstOrderToday) { + $awardAmount = SystemConfig::query()->where(['type' => 1, 'menu_name' => 'award_each_order'])->value('value'); + // 流水 + $record = [ + 'money' => $awardAmount, + 'note' => '用户下单成功,平台奖励', + 'category' => 4, + ]; + $needAward = true; + } + } + + if ($needAward && $awardAmount) { + // 奖励钱包 + $store->refresh(); + $store->award_money = bcadd($store->award_money, $awardAmount, 2); + $store->save(); + + // 流水 + StoreAccount::query()->insert(array($recordBase, $record)); + + // 发布公众号消息 + $openid = Users::query()->where(['id' => $store['user_id']])->value('openid'); + $res = $this->miniprogramService->sendTemMsgForAward($record['money'], $record['note'], $openid, $recordBase['time']); + } + } + + // 喇叭通知,兼容旧音响,MQTT+IOT + $res = $this->mqttSpeakerService->speakToStore($orderMain->id); + $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); + + // 公众号模板消息 + $res = $this->miniprogramService->sendTemMsgForOfflineOrder($orderMain->id); + + Db::commit(); + return true; + + } catch (Exception $e) { $this->log->event( LogLabel::PAY_NOTIFY_WXMINI, - $wxOrder + ['exception_fail' => $e->getMessage()] ); - - // return true; + Db::rollBack(); + $fail('Exception'); } + }); - $response->send(); + return $this->response + ->withHeader('Content-Type', 'text/xml') + ->withStatus(200) + ->withBody(new SwooleStream($response->getContent())); } } \ No newline at end of file diff --git a/app/Model/StoreAccount.php b/app/Model/StoreAccount.php new file mode 100644 index 0000000..d83f11f --- /dev/null +++ b/app/Model/StoreAccount.php @@ -0,0 +1,9 @@ + &$item) { - $item = (array)$item; - // 订单商品 $order_goods = OrderGoods::query()->select(['name', 'number', 'spec', 'good_unit']) ->where(['order_id' => $item['id']]) @@ -91,6 +92,67 @@ class MiniprogramService implements MiniprogramServiceInterface } + /** + * @inheritDoc + */ + public function sendTemMsgForOfflineOrder($order_main_id) + { + + // 查询子订单,用于发消息给商户 + $order_children = Order::query()->select(['id', 'order_num', 'store_id', 'money', 'time']) + ->where(['order_main_id' => $order_main_id]) + ->get() + ->toArray(); + + foreach ($order_children as $key => &$item) { + // 商户/门店的openid + $store = Store::query()->select(['id', 'name', 'user_id']) + ->where(['id' => $item['store_id']]) + ->first()->toArray(); + $store['openid'] = Users::query() + ->where(['id' => $store['user_id']]) + ->value('openid'); + + // 模板数据 + $data_store = [ + 'first' => '您有新订单收入!订单编号:'.$item['order_num'], + 'keyword' => [ + $store['name']?:'', + $item['time']?:'', + '暂无', + $item['money'] + ], + 'remark' => '感谢您的使用!' + ]; + + $ret_store = $this->sendTempMsg($store['openid'], 'lxVbC6PVpKbiO44bYqLmacl-BaME70D47Q0jn2Link0',$data_store); + } + + } + + /** + * @inheritDoc + */ + public function sendTemMsgForAward($money, $note, $openid, $time) + { + // 模板数据发送消息给用户 + $data_user = [ + 'first' => '恭喜!您有一笔新的奖励收入!', + 'keyword' => [ + $money, + $note, + $time + ], + 'remark' => '感谢您的使用!' + ]; + + // 获取用户openid,发送给用户 + $ret_user = $this->sendTempMsg($openid,'ypZ7xdHUjWrRG8P-MD42dhpp6kUlh4Unoh7eTSrLZEg', $data_user); + } + + /** + * @inheritDoc + */ public function sendTempMsg($openid, $template_id, $data, $redirect_url = '', $applet_config = ['appid' => '', 'pagepath' => '']) { // 先拼个基础的 diff --git a/app/Service/MiniprogramServiceInterface.php b/app/Service/MiniprogramServiceInterface.php index b1ebe72..1be9d80 100644 --- a/app/Service/MiniprogramServiceInterface.php +++ b/app/Service/MiniprogramServiceInterface.php @@ -4,6 +4,38 @@ namespace App\Service; interface MiniprogramServiceInterface { + /** + * 外卖线上订单模板消息 + * @param $order_main_id + * @return mixed + */ public function sendTemMsgForOnlineOrder($order_main_id); + + /** + * 当面线下订单模板消息 + * @param $order_main_id + * @return mixed + */ + public function sendTemMsgForOfflineOrder($order_main_id); + + /** + * 奖励模板消息 + * @param $money + * @param $note + * @param $openid + * @param $time + * @return mixed + */ + public function sendTemMsgForAward($money, $note, $openid, $time); + + /** + * 发送模板消息 + * @param $openid + * @param $template_id + * @param $data + * @param string $redirect_url + * @param string[] $applet_config + * @return mixed + */ public function sendTempMsg($openid, $template_id, $data, $redirect_url = '', $applet_config = ['appid' => '', 'pagepath' => '']); } \ No newline at end of file diff --git a/app/Service/UserService.php b/app/Service/UserService.php new file mode 100644 index 0000000..6881a6f --- /dev/null +++ b/app/Service/UserService.php @@ -0,0 +1,76 @@ +where(['user_id' => $user_id]) + ->where(function ($query){ + $query->where('state', 'in', [4,5,10]) + ->orWhere('dm_state', 'in', [2,3]); + }) + ->exists(); + + return !$exist; + } + + /** + * 根据用户的openid更新unionid信息 + * 如果没有找到用户,则不做任何处理 + * @param $openid + * @param $unionid + * @return array + */ + public function saveUserUnionid($openid,$unionid) + { + $result = [ + 'status' => false, + 'msg' => '用户不存在或者已存在相同unionid' + ]; + + // 查询用户是否存在 + $userinfo = Users::select('id','unionid')->where('openid',$openid)->first(); + if($userinfo && $userinfo->unionid != $unionid){ + $userinfo->unionid = $unionid; + if($res = $userinfo->save()){ + $result['status'] = true; + $result['msg'] = '更改用户unionid信息成功'; + $result['res'] = $res; + }else{ + $result['msg'] = '更改用户unionid信息失败'; + } + } + + return $result; + } + + /** + * @inheritDoc + */ + public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id, $limit_amount = 3) + { + return !Order::query() + ->where(['user_id' => $user_id, 'store_id' => $store_id, 'dm_state' => 2]) + ->where('time_add', '>=', date('Y-m-d 00:00:00')) + ->where('time_add', '<=', date('Y-m-d 23:59:59')) + ->where('money', '>=', $limit_amount) + ->where('id', '!=', $current_order_id) + ->exists(); + } +} \ No newline at end of file diff --git a/app/Service/UserServiceInterface.php b/app/Service/UserServiceInterface.php new file mode 100644 index 0000000..5f7bbd3 --- /dev/null +++ b/app/Service/UserServiceInterface.php @@ -0,0 +1,28 @@ + Date: Fri, 14 Aug 2020 13:25:35 +0800 Subject: [PATCH 141/172] =?UTF-8?q?=E5=BD=93=E9=9D=A2=E4=BB=98=E6=94=AF?= =?UTF-8?q?=E4=BB=98=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 23 ++++++++++++++++++++--- app/Service/OrderService.php | 1 + 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 7d88a32..231a0ae 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -207,6 +207,7 @@ class NotifyController extends BaseController public function wxminiOffline() { + var_dump('Inside'); $config = config('wxpay'); $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; @@ -223,6 +224,7 @@ class NotifyController extends BaseController // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { + var_dump('$message', $message); Db::beginTransaction(); try { // 支付失败或者通知失败 @@ -266,12 +268,23 @@ class NotifyController extends BaseController $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime); $orderMain->save(); + var_dump('$orderMain', $orderMain->toArray()); + + $upOrder = Order::query() + ->where(['order_main_id' => $orderMain->id]) + ->update([ + 'state' => OrderMain::ORDER_STATE_UNTAKE, + 'dm_state' => OrderMain::ORDER_STATE_UNTAKE, + 'pay_time' => date('Y-m-d H:i:s', $currentTime) + ]); + + var_dump('$upOrder', $upOrder); // 查询子订单,当面付目前实际上只有一个子订单 $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'pay_time']) ->where(['order_main_id' => $orderMain->id]) ->get() ->toArray(); - + var_dump('$orders', $orders); // 商户钱包、流水资金、奖励、发布模板消息处理 foreach ($orders as $key => $orderItem) { @@ -295,7 +308,7 @@ class NotifyController extends BaseController 'note' => '当面付订单收入', 'category' => 2, ]; - StoreAccount::query()->insert(array($recordBase, $record)); + StoreAccount::query()->insert(array_merge($recordBase, $record)); // 平台新用户奖励给商户 $isStageNewUser = $this->userService->isStageNewUser($orderItem['user_id']); @@ -331,20 +344,24 @@ class NotifyController extends BaseController $store->save(); // 流水 - StoreAccount::query()->insert(array($recordBase, $record)); + StoreAccount::query()->insert(array_merge($recordBase, $record)); // 发布公众号消息 $openid = Users::query()->where(['id' => $store['user_id']])->value('openid'); $res = $this->miniprogramService->sendTemMsgForAward($record['money'], $record['note'], $openid, $recordBase['time']); + var_dump('$res-award', $res); } } // 喇叭通知,兼容旧音响,MQTT+IOT $res = $this->mqttSpeakerService->speakToStore($orderMain->id); + var_dump('$res-mqttSpeakerService', $res); $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); + var_dump('$res-deviceService', $res); // 公众号模板消息 $res = $this->miniprogramService->sendTemMsgForOfflineOrder($orderMain->id); + var_dump('$res-miniprogramService', $res); Db::commit(); return true; diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 75bca49..2ea3245 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -418,6 +418,7 @@ class OrderService implements OrderServiceInterface 'store_id' => $data['store_id'], 'order_main_id' => $orderMainId, 'state' => OrderMain::ORDER_STATE_UNPAY, + 'dm_state' => OrderMain::ORDER_STATE_UNPAY, 'tel' => $orderMain->tel, 'name' => $orderMain->name, 'address' => $orderMain->address, From 0dd1daed41f7a5327dc4b5d6fe367a4412e3b9db Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 13:33:41 +0800 Subject: [PATCH 142/172] =?UTF-8?q?=E5=BD=93=E9=9D=A2=E4=BB=98=E4=B8=8B?= =?UTF-8?q?=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/OrderService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 2ea3245..9e9604a 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -431,7 +431,7 @@ class OrderService implements OrderServiceInterface 'lng' => $orderMain->lng, 'pay_type' => $orderMain->pay_type, 'order_type' => $orderMain->order_type, - 'money' => 0, + 'money' => $data['money'], 'box_money' => 0, 'mj_money' => 0, 'yhq_money' => 0, From e686bb6db34b361b5c06ef67bbad1024f4c109f4 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 14:17:20 +0800 Subject: [PATCH 143/172] =?UTF-8?q?=E5=8E=BB=E6=8E=89=E8=B0=83=E8=AF=95?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 231a0ae..a94b07f 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -207,7 +207,7 @@ class NotifyController extends BaseController public function wxminiOffline() { - var_dump('Inside'); + $config = config('wxpay'); $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; @@ -224,7 +224,6 @@ class NotifyController extends BaseController // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - var_dump('$message', $message); Db::beginTransaction(); try { // 支付失败或者通知失败 @@ -268,8 +267,6 @@ class NotifyController extends BaseController $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime); $orderMain->save(); - var_dump('$orderMain', $orderMain->toArray()); - $upOrder = Order::query() ->where(['order_main_id' => $orderMain->id]) ->update([ @@ -278,13 +275,12 @@ class NotifyController extends BaseController 'pay_time' => date('Y-m-d H:i:s', $currentTime) ]); - var_dump('$upOrder', $upOrder); // 查询子订单,当面付目前实际上只有一个子订单 $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'pay_time']) ->where(['order_main_id' => $orderMain->id]) ->get() ->toArray(); - var_dump('$orders', $orders); + // 商户钱包、流水资金、奖励、发布模板消息处理 foreach ($orders as $key => $orderItem) { @@ -349,19 +345,15 @@ class NotifyController extends BaseController // 发布公众号消息 $openid = Users::query()->where(['id' => $store['user_id']])->value('openid'); $res = $this->miniprogramService->sendTemMsgForAward($record['money'], $record['note'], $openid, $recordBase['time']); - var_dump('$res-award', $res); } } // 喇叭通知,兼容旧音响,MQTT+IOT $res = $this->mqttSpeakerService->speakToStore($orderMain->id); - var_dump('$res-mqttSpeakerService', $res); $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); - var_dump('$res-deviceService', $res); // 公众号模板消息 $res = $this->miniprogramService->sendTemMsgForOfflineOrder($orderMain->id); - var_dump('$res-miniprogramService', $res); Db::commit(); return true; From 058afbe306f2a287aec062e1082c2c0ae8d98904 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 14:36:07 +0800 Subject: [PATCH 144/172] =?UTF-8?q?=E5=B0=86MQTTClient=E7=A7=BB=E5=87=BAta?= =?UTF-8?q?sk?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/MqttServiceInterface.php | 17 ++++++++ app/Service/MqttSpeakerService.php | 46 ++++++++++++++++++-- app/TaskWorker/MQTTClientTask.php | 65 ---------------------------- 3 files changed, 60 insertions(+), 68 deletions(-) delete mode 100644 app/TaskWorker/MQTTClientTask.php diff --git a/app/Service/MqttServiceInterface.php b/app/Service/MqttServiceInterface.php index 203b908..127b3cc 100644 --- a/app/Service/MqttServiceInterface.php +++ b/app/Service/MqttServiceInterface.php @@ -18,4 +18,21 @@ interface MqttServiceInterface * @return mixed */ public function pubToMqtt($message, $topic, $toClientId); + + /** + * @param string|number $message 消息内容 + * @param string $topic 发布消息到主题,主题名 + * @param string $type 消息类型,cash或tts + * @param string $payId 支付方式,如“支付宝”、“微信”等 + * @param string $toClientId 终端id,如IMEI码 + * @param string $curClientId 当前客户端id + */ + public function publish( + $message, + $topic, + $toClientId = '', + $type = '', + $payId = '', + $curClientId = '' + ); } \ No newline at end of file diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index 5a8b802..4eaf580 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -2,9 +2,9 @@ namespace App\Service; +use App\Libs\MQTTClient; use App\Model\Order; use App\Model\Store; -use App\TaskWorker\MQTTClientTask; use Hyperf\Utils\ApplicationContext; class MqttSpeakerService implements MqttServiceInterface @@ -43,7 +43,47 @@ class MqttSpeakerService implements MqttServiceInterface */ public function pubToMqtt($message, $topic, $toClientId) { - $task = ApplicationContext::getContainer()->get(MQTTClientTask::class); - $task->publish($message, $topic, $toClientId); + $this->publish($message, $topic, $toClientId); + } + + /** + * @inheritDoc + */ + public function publish( + $message, + $topic, + $toClientId = '', + $type = '', + $payId = '', + $curClientId = '' + ) { + + $client = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT')); + $client->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS')); + + if (env('MQTT_CERT')) { + $client->setEncryption(env('MQTT_CERT')); + } + + $msgArr = []; + if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) { + $msgArr['cash'] = $message; + $payId AND $msgArr['payid'] = $payId; + } else { + $msgArr['message'] = $message; + } + + if (!empty($toClientId)) { + $topic .= '/'.$toClientId; + } + + $curClientId OR $curClientId = (string)rand(1,999999999); + $success = $client->sendConnect($curClientId); + + if ($success) { + $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2); + $client->sendDisconnect(); + } + $client->close(); } } \ No newline at end of file diff --git a/app/TaskWorker/MQTTClientTask.php b/app/TaskWorker/MQTTClientTask.php deleted file mode 100644 index e49f562..0000000 --- a/app/TaskWorker/MQTTClientTask.php +++ /dev/null @@ -1,65 +0,0 @@ -getClient(); - - $msgArr = []; - if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) { - $msgArr['cash'] = $message; - $payId AND $msgArr['payid'] = $payId; - } else { - $msgArr['message'] = $message; - } - - if (!empty($toClientId)) { - $topic .= '/'.$toClientId; - } - - $curClientId OR $curClientId = (string)rand(1,999999999); - $success = $this->mqttClient->sendConnect($curClientId); - - if ($success) { - $this->mqttClient->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2); - $this->mqttClient->sendDisconnect(); - } - $this->mqttClient->close(); - } - - protected function getClient() - { - $this->mqttClient = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT')); - $this->mqttClient->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS')); - - if (env('MQTT_CERT')) { - $this->mqttClient->setEncryption(env('MQTT_CERT')); - } - - return $this->mqttClient; - } -} \ No newline at end of file From 8133c86dc5ce0a60e9f61fe219c38fc16ca91494 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 14:48:14 +0800 Subject: [PATCH 145/172] debug mqttclient --- app/Service/MqttServiceInterface.php | 9 --------- app/Service/MqttSpeakerService.php | 19 ++++++++----------- 2 files changed, 8 insertions(+), 20 deletions(-) diff --git a/app/Service/MqttServiceInterface.php b/app/Service/MqttServiceInterface.php index 127b3cc..3148be2 100644 --- a/app/Service/MqttServiceInterface.php +++ b/app/Service/MqttServiceInterface.php @@ -10,15 +10,6 @@ interface MqttServiceInterface */ public function speakToStore($orderId, $isMain = true); - /** - * MQTT发布消息 - * @param $message - * @param $topic - * @param $toClientId - * @return mixed - */ - public function pubToMqtt($message, $topic, $toClientId); - /** * @param string|number $message 消息内容 * @param string $topic 发布消息到主题,主题名 diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index 4eaf580..080e0c1 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -17,7 +17,7 @@ class MqttSpeakerService implements MqttServiceInterface */ public function speakToStore($orderId, $isMain = true) { - + var_dump('speaker-orderid', $orderId); // 获取订单 $orders = Order::query()->select(['id','order_num','money', 'pay_type', 'store_id', 'type']); if ($isMain) { @@ -26,26 +26,22 @@ class MqttSpeakerService implements MqttServiceInterface $orders = $orders->where(['id' => $orderId])->get()->toArray(); } + var_dump('speaker-orders', $orders); + if(empty($orders)) return; // 循环发送 foreach ($orders as $k => &$order) { - $order['template'] = "懒族生活支付到账".floatval($order['money'])."元"; + $order['template'] = "懒族支付到账".floatval($order['money'])."元"; // 获取终端ID $order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei'); + var_dump('speaker-$order', $order); // 发布订阅消息 - $this->pubToMqtt($order['template'], self::TOPIC, $order['to_client_id']); + $res = $this->publish($order['template'], self::TOPIC, $order['to_client_id']); + var_dump('speaker-$res', $res); } } - /** - * @inheritDoc - */ - public function pubToMqtt($message, $topic, $toClientId) - { - $this->publish($message, $topic, $toClientId); - } - /** * @inheritDoc */ @@ -60,6 +56,7 @@ class MqttSpeakerService implements MqttServiceInterface $client = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT')); $client->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS')); + $client->setDebug(true); if (env('MQTT_CERT')) { $client->setEncryption(env('MQTT_CERT')); From 4da66fe1f9892112f5e520813125ae2ff64f71e7 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Fri, 14 Aug 2020 14:51:32 +0800 Subject: [PATCH 146/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E4=B8=BA=E6=AD=A3=E5=BC=8Foos=E7=9A=84=E8=B7=AF?= =?UTF-8?q?=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponService.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 9fc4f97..6708822 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -45,8 +45,8 @@ class CouponService implements CouponServiceInterface 'jump_data' => [ 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, - 'share_bg' => env('OSS_IMG_HOST').'/attachment/images/png/2020/08/11/d697d43b91913f861f931649f0898815.png', - 'receive_bg' => env('OSS_IMG_HOST')."/attachment/images/png/2020/08/11/9c7d7c95b5de29539fad4bc9a2fcb98d.png", + 'share_bg' => env('OSS_IMG_HOST').'/static/img/coupon_bg.png', + 'receive_bg' => env('OSS_IMG_HOST').'/static/img/coupon_share.png', 'coupons' => [] ] ]; From 24df57265e413b28aee13bf0a475eb4f5dc4c6ae Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 14:54:44 +0800 Subject: [PATCH 147/172] Debug (cherry picked from commit b789d72128d10d4f0d33dc208c055d83685975db) --- app/Libs/MQTTClient.php | 6 +++++- app/Service/MqttSpeakerService.php | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/app/Libs/MQTTClient.php b/app/Libs/MQTTClient.php index 56584c0..7c02ad7 100644 --- a/app/Libs/MQTTClient.php +++ b/app/Libs/MQTTClient.php @@ -218,6 +218,8 @@ class MQTTClient { * @return boolean Returns false if connection failed */ public function sendConnect($clientId, $cleanSession=false, $keepAlive=10, $timeout=5000) { + + var_dump('serverAddress', $this->serverAddress); if (!$this->serverAddress) return false; // Basic validation of clientid @@ -390,8 +392,9 @@ class MQTTClient { * @return boolean */ public function sendPublish($topic, $message, $qos = self::MQTT_QOS1, $retain = 0) { + var_dump('connect:', $this->isConnected()); if(!$this->isConnected()) return false; - +var_dump('sendpublish', [$topic, $message, $qos]); if($qos!=self::MQTT_QOS0 && $qos!=self::MQTT_QOS1 && $qos!=self::MQTT_QOS2) return false; $packetId = $this->getNextPacketId(); @@ -405,6 +408,7 @@ class MQTTClient { $dupFlag = 0; $header = $this->createHeader(self::MQTT_PUBLISH + ($dupFlag<<3) + ($qos<<1) + $retain, $payload); $this->debugMessage('Sending PUBLISH'); + var_dump('sendpublish-$payload', $header.$payload); $this->send($header . $payload); if($qos == self::MQTT_QOS1) { diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index 080e0c1..617eb3a 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -76,7 +76,7 @@ class MqttSpeakerService implements MqttServiceInterface $curClientId OR $curClientId = (string)rand(1,999999999); $success = $client->sendConnect($curClientId); - + var_dump('$success', $success); if ($success) { $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2); $client->sendDisconnect(); From 8145b74169ef66c9e12663f2d4ca5b60d1f70dd0 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 15:04:00 +0800 Subject: [PATCH 148/172] =?UTF-8?q?=E5=8E=BB=E6=8E=89Debug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Libs/MQTTClient.php | 4 ---- app/Service/MqttSpeakerService.php | 7 +------ 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/app/Libs/MQTTClient.php b/app/Libs/MQTTClient.php index 7c02ad7..0d08a87 100644 --- a/app/Libs/MQTTClient.php +++ b/app/Libs/MQTTClient.php @@ -219,7 +219,6 @@ class MQTTClient { */ public function sendConnect($clientId, $cleanSession=false, $keepAlive=10, $timeout=5000) { - var_dump('serverAddress', $this->serverAddress); if (!$this->serverAddress) return false; // Basic validation of clientid @@ -392,9 +391,7 @@ class MQTTClient { * @return boolean */ public function sendPublish($topic, $message, $qos = self::MQTT_QOS1, $retain = 0) { - var_dump('connect:', $this->isConnected()); if(!$this->isConnected()) return false; -var_dump('sendpublish', [$topic, $message, $qos]); if($qos!=self::MQTT_QOS0 && $qos!=self::MQTT_QOS1 && $qos!=self::MQTT_QOS2) return false; $packetId = $this->getNextPacketId(); @@ -408,7 +405,6 @@ var_dump('sendpublish', [$topic, $message, $qos]); $dupFlag = 0; $header = $this->createHeader(self::MQTT_PUBLISH + ($dupFlag<<3) + ($qos<<1) + $retain, $payload); $this->debugMessage('Sending PUBLISH'); - var_dump('sendpublish-$payload', $header.$payload); $this->send($header . $payload); if($qos == self::MQTT_QOS1) { diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index 617eb3a..d058ae7 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -17,7 +17,7 @@ class MqttSpeakerService implements MqttServiceInterface */ public function speakToStore($orderId, $isMain = true) { - var_dump('speaker-orderid', $orderId); + // 获取订单 $orders = Order::query()->select(['id','order_num','money', 'pay_type', 'store_id', 'type']); if ($isMain) { @@ -26,8 +26,6 @@ class MqttSpeakerService implements MqttServiceInterface $orders = $orders->where(['id' => $orderId])->get()->toArray(); } - var_dump('speaker-orders', $orders); - if(empty($orders)) return; // 循环发送 @@ -35,10 +33,8 @@ class MqttSpeakerService implements MqttServiceInterface $order['template'] = "懒族支付到账".floatval($order['money'])."元"; // 获取终端ID $order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei'); - var_dump('speaker-$order', $order); // 发布订阅消息 $res = $this->publish($order['template'], self::TOPIC, $order['to_client_id']); - var_dump('speaker-$res', $res); } } @@ -76,7 +72,6 @@ class MqttSpeakerService implements MqttServiceInterface $curClientId OR $curClientId = (string)rand(1,999999999); $success = $client->sendConnect($curClientId); - var_dump('$success', $success); if ($success) { $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2); $client->sendDisconnect(); From 0e3687e697e3a3fa75091534286f0f47b6688121 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Fri, 14 Aug 2020 17:48:55 +0800 Subject: [PATCH 149/172] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E7=94=A8=E6=88=B7uni?= =?UTF-8?q?onid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + app/Controller/UserController.php | 31 ++++++++++++++ app/Request/UserUnionidRequest.php | 45 ++++++++++++++++++++ app/Service/UserService.php | 63 ++++++++++++++++++++++++++++ app/Service/UserServiceInterface.php | 18 ++++++++ config/routes.php | 23 ++++++++++ 6 files changed, 181 insertions(+) create mode 100644 app/Controller/UserController.php create mode 100644 app/Request/UserUnionidRequest.php create mode 100644 app/Service/UserService.php create mode 100644 app/Service/UserServiceInterface.php diff --git a/.gitignore b/.gitignore index 9091e68..8088c1b 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ vendor/ *.lock .phpunit* /watch +.vscode/settings.json diff --git a/app/Controller/UserController.php b/app/Controller/UserController.php new file mode 100644 index 0000000..d494d83 --- /dev/null +++ b/app/Controller/UserController.php @@ -0,0 +1,31 @@ +request->input('openid',''); + $unionid = $this->request->input('unionid',''); + + return $this->success($this->userService->saveUserUnionid($openid,$unionid)); + } + +} diff --git a/app/Request/UserUnionidRequest.php b/app/Request/UserUnionidRequest.php new file mode 100644 index 0000000..939940f --- /dev/null +++ b/app/Request/UserUnionidRequest.php @@ -0,0 +1,45 @@ + 'required|nonempty', + 'unionid' => 'required|nonempty', + ]; + } + + public function messages(): array + { + return [ + 'openid.*' => ':attribute必须', + 'unionid.*' => ':attribute必须', + ]; + } + + public function attributes(): array + { + return [ + 'openid' => '用户openid', + 'unionid' => '用户unionid', + ]; + } +} diff --git a/app/Service/UserService.php b/app/Service/UserService.php new file mode 100644 index 0000000..87606c1 --- /dev/null +++ b/app/Service/UserService.php @@ -0,0 +1,63 @@ +where(['user_id' => $user_id]) + ->where(function ($query){ + $query->where('state', 'in', [4,5,10]) + ->orWhere('dm_state', 'in', [2,3]); + }) + ->exists(); + + return !$exist; + } + + /** + * 根据用户的openid更新unionid信息 + * 如果没有找到用户,则不做任何处理 + * @param $openid + * @param $unionid + * @return array + */ + public function saveUserUnionid($openid,$unionid) + { + $result = [ + 'status' => false, + 'msg' => '用户不存在或者已存在相同unionid' + ]; + + // 查询用户是否存在 + $userinfo = Users::select('id','unionid')->where('openid',$openid)->first(); + if($userinfo && $userinfo->unionid != $unionid){ + $userinfo->unionid = $unionid; + if($res = $userinfo->save()){ + $result['status'] = true; + $result['msg'] = '更改用户unionid信息成功'; + $result['res'] = $res; + }else{ + $result['msg'] = '更改用户unionid信息失败'; + } + } + + return $result; + } + + +} \ No newline at end of file diff --git a/app/Service/UserServiceInterface.php b/app/Service/UserServiceInterface.php new file mode 100644 index 0000000..06c1ea0 --- /dev/null +++ b/app/Service/UserServiceInterface.php @@ -0,0 +1,18 @@ + Date: Fri, 14 Aug 2020 18:09:43 +0800 Subject: [PATCH 150/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E4=BD=BF?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/OrderService.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 9e9604a..9efaf6b 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -46,6 +46,7 @@ class OrderService implements OrderServiceInterface // 计算当前订单可用红包优惠金额 $couponMoney = 0; + $receiveCouponIds = []; if (isset($data['receive_coupon_ids'])&&$data['receive_coupon_ids']) { $receiveCouponIds = explode(',', str_replace(',',',',$data['receive_coupon_ids'])); $couponMoney = $this->getCouponAmount($receiveCouponIds, $data['money'], $data['user_id'], $data['market_id']); @@ -290,6 +291,11 @@ class OrderService implements OrderServiceInterface if (is_array($canUseConpons)&&!empty($canUseConpons)) { # 使用记录、更新当前优惠券 foreach ($canUseConpons as $key => &$coupon) { + + if (!in_array($coupon->id, $receiveCouponIds)) { + continue; + } + $couponUse = [ 'user_id' => $coupon->user_id, 'user_receive_id' => $coupon->id, From 08648047bd6c6bde0d260b03245243aeaa0690b6 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 20:13:30 +0800 Subject: [PATCH 151/172] hot_fix --- app/Amqp/Consumer/couponRebateConsumer.php | 2 +- composer.json | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index 239aee7..bca6310 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -16,7 +16,7 @@ use Hyperf\Di\Annotation\Inject; /** - * @Consumer(exchange="couponRebate1", routingKey="couponRebate1", queue="couponRebate1", name ="couponRebateConsumer", nums=1) + * @Consumer(exchange="couponRebate", routingKey="couponRebate", queue="couponRebate", name ="couponRebateConsumer", nums=1) */ class couponRebateConsumer extends ConsumerMessage { diff --git a/composer.json b/composer.json index 5553ffb..6c643dd 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,9 @@ "xxtime/flysystem-aliyun-oss": "^1.5", "hyperf/validation": "^2.0", "hyperf/task": "^2.0", - "hyperf/paginator": "^2.0" + "hyperf/paginator": "^2.0", + "hyperf/amqp": "^2.0", + "alibabacloud/iot": "^1.8" }, "require-dev": { "swoole/ide-helper": "^4.5", From 11e2bf44cd57029153e4e6598ca78467280d4a7a Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Fri, 14 Aug 2020 20:13:48 +0800 Subject: [PATCH 152/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9amqp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/couponRebateConsumer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Amqp/Consumer/couponRebateConsumer.php b/app/Amqp/Consumer/couponRebateConsumer.php index 239aee7..bca6310 100644 --- a/app/Amqp/Consumer/couponRebateConsumer.php +++ b/app/Amqp/Consumer/couponRebateConsumer.php @@ -16,7 +16,7 @@ use Hyperf\Di\Annotation\Inject; /** - * @Consumer(exchange="couponRebate1", routingKey="couponRebate1", queue="couponRebate1", name ="couponRebateConsumer", nums=1) + * @Consumer(exchange="couponRebate", routingKey="couponRebate", queue="couponRebate", name ="couponRebateConsumer", nums=1) */ class couponRebateConsumer extends ConsumerMessage { From d9bc4c7d46594f0af12f79b76c38487cc8afecb4 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 20:22:43 +0800 Subject: [PATCH 153/172] hot_fix_2 --- app/Service/CouponService.php | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 6708822..01895a8 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -108,16 +108,23 @@ class CouponService implements CouponServiceInterface ->orderBy('u.weigh','desc') ->get(); - foreach ($coupons as $k => &$v){ - - if($v->active_type == 1 && count($result['not_receive']) < 4){ - $result['not_receive'][] = $v; - }else if($v->active_type == 2 && in_array($v->id,$couponReceiveIds)){ - $result['jump_data']['coupons'][] = $v->id; + foreach ($coupons as $key => $coupon) { + //拼接满减文字提示 + $coupon->full_amount_text = '满' . $coupon->full_amount . "可用"; + //判断是折扣优惠券还是满减优惠券 + if($coupon->discount_type == 1){ + $coupon->discounts_text = '¥'.$coupon->discounts; + }elseif($coupon->discount_type == 2){ + $coupon->discounts_text = floatval($coupon->discounts)."折"; } - - if($v->discount_type == 2){ - $v->discounts = floatval($v->discounts); + //失效时间格式转换 + $usable_end_time = date('Y-m-d H:i:s',$coupon->usable_end_time); + $coupon->usable_end_time_text = '有效期至:'.$usable_end_time; + + if ($coupon->usable_end_time < $nowTime || $coupon->number_remain <= 0) { + $expired[] = $coupon; + } else { + $not_expired[] = $coupon; } } From 2651fe4fb7cdea94243a664f85009792eb5db2a4 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 20:27:34 +0800 Subject: [PATCH 154/172] hot_fix_3 --- app/Controller/CouponController.php | 12 ++++++++++++ app/Service/CouponService.php | 25 +++++++++---------------- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/app/Controller/CouponController.php b/app/Controller/CouponController.php index 648039a..e34cd85 100644 --- a/app/Controller/CouponController.php +++ b/app/Controller/CouponController.php @@ -158,6 +158,18 @@ class CouponController extends BaseController ->get(); foreach ($coupons as $key => $coupon) { + //拼接满减文字提示 + $coupon->full_amount_text = '满' . $coupon->full_amount . "可用"; + //判断是折扣优惠券还是满减优惠券 + if($coupon->discount_type == 1){ + $coupon->discounts_text = '¥'.$coupon->discounts; + }elseif($coupon->discount_type == 2){ + $coupon->discounts_text = floatval($coupon->discounts)."折"; + } + //失效时间格式转换 + $usable_end_time = date('Y-m-d H:i:s',$coupon->usable_end_time); + $coupon->usable_end_time_text = '有效期至:'.$usable_end_time; + if ($coupon->usable_end_time < $nowTime || $coupon->number_remain <= 0) { $expired[] = $coupon; } else { diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 01895a8..40b51af 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -108,23 +108,16 @@ class CouponService implements CouponServiceInterface ->orderBy('u.weigh','desc') ->get(); - foreach ($coupons as $key => $coupon) { - //拼接满减文字提示 - $coupon->full_amount_text = '满' . $coupon->full_amount . "可用"; - //判断是折扣优惠券还是满减优惠券 - if($coupon->discount_type == 1){ - $coupon->discounts_text = '¥'.$coupon->discounts; - }elseif($coupon->discount_type == 2){ - $coupon->discounts_text = floatval($coupon->discounts)."折"; + foreach ($coupons as $k => &$v){ + + if($v->active_type == 1 && count($result['not_receive']) < 4){ + $result['not_receive'][] = $v; + }else if($v->active_type == 2 && in_array($v->id,$couponReceiveIds)){ + $result['jump_data']['coupons'][] = $v->id; } - //失效时间格式转换 - $usable_end_time = date('Y-m-d H:i:s',$coupon->usable_end_time); - $coupon->usable_end_time_text = '有效期至:'.$usable_end_time; - - if ($coupon->usable_end_time < $nowTime || $coupon->number_remain <= 0) { - $expired[] = $coupon; - } else { - $not_expired[] = $coupon; + + if($v->discount_type == 2){ + $v->discounts = floatval($v->discounts); } } From 2e22315ea2d957a29fad3f3d0fd31aef7f450dd3 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 20:51:01 +0800 Subject: [PATCH 155/172] =?UTF-8?q?banner=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/AdService.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/Service/AdService.php b/app/Service/AdService.php index 77170ac..997e9a8 100644 --- a/app/Service/AdService.php +++ b/app/Service/AdService.php @@ -15,6 +15,8 @@ class AdService implements AdServiceInterface ->where([ 'type' => Ad::TYPE_BANNER, 'status' => Ad::STATUS_YES - ])->get(); + ]) + ->orderBy('orderby', 'desc') + ->get(); } } \ No newline at end of file From 1210e96c38f1f1a78b297980c7a31663a68ff028 Mon Sep 17 00:00:00 2001 From: liangyuyan <1103300295@qq.com> Date: Fri, 14 Aug 2020 21:48:13 +0800 Subject: [PATCH 156/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8=E6=B4=BB=E5=8A=A8--=E4=BF=AE=E6=94=B9=E8=83=8C?= =?UTF-8?q?=E6=99=AF=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/CouponService.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index 40b51af..5537d97 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -45,8 +45,8 @@ class CouponService implements CouponServiceInterface 'jump_data' => [ 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType, - 'share_bg' => env('OSS_IMG_HOST').'/static/img/coupon_bg.png', - 'receive_bg' => env('OSS_IMG_HOST').'/static/img/coupon_share.png', + 'share_bg' => env('OSS_IMG_HOST').'/static/img/coupon_share.png', + 'receive_bg' => env('OSS_IMG_HOST').'/static/img/coupon_bg.png', 'coupons' => [] ] ]; From 38d7035b883eba51409cf1d0e75643a2ca52ba29 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 10:36:33 +0800 Subject: [PATCH 157/172] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=B7=A8=E5=BA=97?= =?UTF-8?q?=E4=B8=8B=E5=8D=95=E5=95=86=E5=93=81=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/OrderService.php | 29 +++++++---------------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 9efaf6b..d8d0bdd 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -99,6 +99,7 @@ class OrderService implements OrderServiceInterface // 循环处理订单总额、子订单总额、商品、商户订单等信息 $orderAmountTotal = 0; # 总订单金额 + $orderGoods = []; foreach ($storeList as $key => &$item) { // 子订单数据处理 @@ -142,7 +143,7 @@ class OrderService implements OrderServiceInterface // 子订单内商品处理 $goodsAmountTotal = 0; - $orderGoods = []; + if (!is_array($item['good_list'])||empty($item['good_list'])) { Db::rollBack(); return '订单商品异常'; @@ -273,28 +274,12 @@ class OrderService implements OrderServiceInterface } // 处理红包的使用 - $canUseConpons = $this->couponService->getOrderCanUseCoupons( - $data['money'], - $data['market_id'], - $data['user_id'], - [ - 'receive.id', - 'receive.user_id', - 'receive.number', - 'receive.number_remain', - 'receive.system_coupon_user_id', - 'coupon.discounts', - 'coupon.discount_type', - ] - ); - - if (is_array($canUseConpons)&&!empty($canUseConpons)) { + $canUseCoupons = CouponUserRec::select(['id', 'user_id', 'number', 'number_remain', 'system_coupon_user_id']) + ->whereIn('id', $receiveCouponIds) + ->get(); + if (is_array($canUseCoupons)&&!empty($canUseCoupons)) { # 使用记录、更新当前优惠券 - foreach ($canUseConpons as $key => &$coupon) { - - if (!in_array($coupon->id, $receiveCouponIds)) { - continue; - } + foreach ($canUseCoupons as $key => &$coupon) { $couponUse = [ 'user_id' => $coupon->user_id, From 7d831289ac52796392e437649994f2e34c2addbe Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 11:10:16 +0800 Subject: [PATCH 158/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E4=BD=BF?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/OrderService.php | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index d8d0bdd..b637ac3 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -276,15 +276,15 @@ class OrderService implements OrderServiceInterface // 处理红包的使用 $canUseCoupons = CouponUserRec::select(['id', 'user_id', 'number', 'number_remain', 'system_coupon_user_id']) ->whereIn('id', $receiveCouponIds) - ->get(); + ->get()->toArray(); if (is_array($canUseCoupons)&&!empty($canUseCoupons)) { # 使用记录、更新当前优惠券 foreach ($canUseCoupons as $key => &$coupon) { $couponUse = [ - 'user_id' => $coupon->user_id, - 'user_receive_id' => $coupon->id, - 'system_coupon_id' => $coupon->system_coupon_user_id, + 'user_id' => $coupon['user_id'], + 'user_receive_id' => $coupon['id'], + 'system_coupon_id' => $coupon['system_coupon_user_id'], 'order_main_id' => $orderMainId, 'use_time' => $currentTime, 'return_time' => 0, @@ -292,20 +292,21 @@ class OrderService implements OrderServiceInterface 'status' => 1, 'update_time' => 0, ]; + var_dump('$couponUse',$couponUse); $insertRes = CouponUserUse::query()->insert($couponUse); if ($insertRes) { - $numberRemain = $coupon->number_remain - 1; + $numberRemain = $coupon['number_remain'] - 1; if ($numberRemain == 0) { $status = 2; - } elseif ($numberRemain > 0 && $numberRemain < $coupon->number) { + } elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) { $status = 1; - } elseif ($numberRemain == $coupon->number) { + } elseif ($numberRemain == $coupon['number']) { $status = 0; } - $upRes = CouponUserRec::query()->where(['id' => $coupon->id])->update(['number_remain' => $numberRemain, 'status' => $status]); + $upRes = CouponUserRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]); if (!$upRes) { Db::rollBack(); @@ -313,7 +314,7 @@ class OrderService implements OrderServiceInterface } // 缓存使用记录 - $usedRes = $this->couponService->cacheTodayCouponUsed($coupon->user_id, $coupon->system_coupon_user_id, $coupon->id); + $usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']); if (!$usedRes) { Db::rollBack(); return '优惠券使用失败'; From f9b0fce54f0b50e2f11bbdce6a8e411906730e41 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 12:06:25 +0800 Subject: [PATCH 159/172] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 4 ++-- config/autoload/dependencies.php | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index a94b07f..1d2c1be 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -15,7 +15,7 @@ use App\Model\SystemConfig; use App\Model\Users; use App\Service\DeviceServiceInterface; use App\Service\FeiePrintServiceInterface; -use App\Service\MiniprogramService; +use App\Service\MiniprogramServiceInterface; use App\Service\MqttServiceInterface; use App\Service\UserServiceInterface; use EasyWeChat\Factory; @@ -43,7 +43,7 @@ class NotifyController extends BaseController /** * @Inject - * @var MiniprogramService + * @var MiniprogramServiceInterface */ protected $miniprogramService; diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 1557ca3..7c683c7 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -21,4 +21,6 @@ return [ \App\Service\CouponServiceInterface::class => \App\Service\CouponService::class, \App\Service\MqttServiceInterface::class => \App\Service\MqttSpeakerService::class, \App\Service\FeiePrintServiceInterface::class => \App\Service\FeiePrintService::class, + \App\Service\MiniprogramServiceInterface::class => \App\Service\MiniprogramService::class, + \App\Service\UserServiceInterface::class => \App\Service\UserService::class, ]; From 69316fac903b99428cec2cf157573e5a0a41f678 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 18:10:47 +0800 Subject: [PATCH 160/172] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=A5=96=E5=8A=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 4 +++- app/Service/UserService.php | 10 +++++----- app/Service/UserServiceInterface.php | 2 +- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 1d2c1be..fb4de38 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -29,6 +29,8 @@ use Symfony\Component\HttpFoundation\Request; class NotifyController extends BaseController { + const AWARD_LIMIT_AMOUNT = 3; + /** * @Inject * @var MqttServiceInterface @@ -321,7 +323,7 @@ class NotifyController extends BaseController $needAward = true; } else { $isStoreFirstOrderToday = $this->userService->isStoreFirstOrderToday($orderItem['user_id'],$orderItem['store_id'],$orderItem['id']); - if ($isStoreFirstOrderToday) { + if ($isStoreFirstOrderToday && $orderItem['money'] >= self::AWARD_LIMIT_AMOUNT) { $awardAmount = SystemConfig::query()->where(['type' => 1, 'menu_name' => 'award_each_order'])->value('value'); // 流水 $record = [ diff --git a/app/Service/UserService.php b/app/Service/UserService.php index 6881a6f..c045850 100644 --- a/app/Service/UserService.php +++ b/app/Service/UserService.php @@ -22,8 +22,8 @@ class UserService implements UserServiceInterface $exist = OrderMain::query() ->where(['user_id' => $user_id]) ->where(function ($query){ - $query->where('state', 'in', [4,5,10]) - ->orWhere('dm_state', 'in', [2,3]); + $query->where('state', 'in', [OrderMain::ORDER_STATE_COMPLETE,OrderMain::ORDER_STATE_EVALUATED,OrderMain::ORDER_STATE_UNREFUND]) + ->orWhere('dm_state', 'in', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]); }) ->exists(); @@ -63,13 +63,13 @@ class UserService implements UserServiceInterface /** * @inheritDoc */ - public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id, $limit_amount = 3) + public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id) { return !Order::query() - ->where(['user_id' => $user_id, 'store_id' => $store_id, 'dm_state' => 2]) + ->where(['user_id' => $user_id, 'store_id' => $store_id]) + ->whereIn('dm_state', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]) ->where('time_add', '>=', date('Y-m-d 00:00:00')) ->where('time_add', '<=', date('Y-m-d 23:59:59')) - ->where('money', '>=', $limit_amount) ->where('id', '!=', $current_order_id) ->exists(); } diff --git a/app/Service/UserServiceInterface.php b/app/Service/UserServiceInterface.php index 5f7bbd3..2e41493 100644 --- a/app/Service/UserServiceInterface.php +++ b/app/Service/UserServiceInterface.php @@ -23,6 +23,6 @@ interface UserServiceInterface * @param int $limit_amount * @return mixed */ - public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id, $limit_amount = 3); + public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id); } \ No newline at end of file From 378a14b048dce814df024700c3681e735008a7cf Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 18:27:48 +0800 Subject: [PATCH 161/172] =?UTF-8?q?=E5=A5=96=E5=8A=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/UserService.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Service/UserService.php b/app/Service/UserService.php index c045850..a665734 100644 --- a/app/Service/UserService.php +++ b/app/Service/UserService.php @@ -22,8 +22,8 @@ class UserService implements UserServiceInterface $exist = OrderMain::query() ->where(['user_id' => $user_id]) ->where(function ($query){ - $query->where('state', 'in', [OrderMain::ORDER_STATE_COMPLETE,OrderMain::ORDER_STATE_EVALUATED,OrderMain::ORDER_STATE_UNREFUND]) - ->orWhere('dm_state', 'in', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]); + $query->whereIn('state', [OrderMain::ORDER_STATE_COMPLETE,OrderMain::ORDER_STATE_EVALUATED,OrderMain::ORDER_STATE_UNREFUND]) + ->orWhereIn('dm_state', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]); }) ->exists(); From 0785999db0f909ffc057359ecfbae5cf02cffe62 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 18:55:15 +0800 Subject: [PATCH 162/172] =?UTF-8?q?=E5=95=86=E6=88=B7=E5=A5=96=E5=8A=B1?= =?UTF-8?q?=EF=BC=88=E5=B9=B3=E5=8F=B0=E6=96=B0=E7=94=A8=E6=88=B7BUG?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 2 +- app/Service/UserService.php | 4 +++- app/Service/UserServiceInterface.php | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index fb4de38..c762745 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -309,7 +309,7 @@ class NotifyController extends BaseController StoreAccount::query()->insert(array_merge($recordBase, $record)); // 平台新用户奖励给商户 - $isStageNewUser = $this->userService->isStageNewUser($orderItem['user_id']); + $isStageNewUser = $this->userService->isStageNewUser($orderItem['user_id'], $orderMain->id); $needAward = false; $awardAmount = 0; if ($isStageNewUser) { diff --git a/app/Service/UserService.php b/app/Service/UserService.php index a665734..8f43371 100644 --- a/app/Service/UserService.php +++ b/app/Service/UserService.php @@ -15,12 +15,14 @@ class UserService implements UserServiceInterface * 判定条件: * 没有在平台下过单(包括线上和线下) * @param $user_id + * @param $order_main_id * @return mixed|void */ - public function isStageNewUser($user_id): bool + public function isStageNewUser($user_id, $order_main_id): bool { $exist = OrderMain::query() ->where(['user_id' => $user_id]) + ->where('id', '!=', $order_main_id) ->where(function ($query){ $query->whereIn('state', [OrderMain::ORDER_STATE_COMPLETE,OrderMain::ORDER_STATE_EVALUATED,OrderMain::ORDER_STATE_UNREFUND]) ->orWhereIn('dm_state', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]); diff --git a/app/Service/UserServiceInterface.php b/app/Service/UserServiceInterface.php index 2e41493..8742ce9 100644 --- a/app/Service/UserServiceInterface.php +++ b/app/Service/UserServiceInterface.php @@ -9,9 +9,10 @@ interface UserServiceInterface /** * 是否平台新用户 * @param $user_id + * @param $order_main_id * @return mixed */ - public function isStageNewUser($user_id): bool; + public function isStageNewUser($user_id, $order_main_id): bool; public function saveUserUnionid($openid,$unionid); From f5ad8df2d881f0279602e673b2a7346c8f36f55c Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 19:13:42 +0800 Subject: [PATCH 163/172] =?UTF-8?q?=E5=A5=96=E5=8A=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 2 +- app/Service/UserService.php | 3 ++- app/Service/UserServiceInterface.php | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index c762745..9f47c82 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -322,7 +322,7 @@ class NotifyController extends BaseController ]; $needAward = true; } else { - $isStoreFirstOrderToday = $this->userService->isStoreFirstOrderToday($orderItem['user_id'],$orderItem['store_id'],$orderItem['id']); + $isStoreFirstOrderToday = $this->userService->isStoreFirstOrderToday($orderItem['user_id'],$orderItem['store_id'],$orderItem['id'], self::AWARD_LIMIT_AMOUNT); if ($isStoreFirstOrderToday && $orderItem['money'] >= self::AWARD_LIMIT_AMOUNT) { $awardAmount = SystemConfig::query()->where(['type' => 1, 'menu_name' => 'award_each_order'])->value('value'); // 流水 diff --git a/app/Service/UserService.php b/app/Service/UserService.php index 8f43371..b5cc5fb 100644 --- a/app/Service/UserService.php +++ b/app/Service/UserService.php @@ -65,13 +65,14 @@ class UserService implements UserServiceInterface /** * @inheritDoc */ - public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id) + public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id, $limit_amount = 3) { return !Order::query() ->where(['user_id' => $user_id, 'store_id' => $store_id]) ->whereIn('dm_state', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]) ->where('time_add', '>=', date('Y-m-d 00:00:00')) ->where('time_add', '<=', date('Y-m-d 23:59:59')) + ->where('money', '>=', $limit_amount) ->where('id', '!=', $current_order_id) ->exists(); } diff --git a/app/Service/UserServiceInterface.php b/app/Service/UserServiceInterface.php index 8742ce9..2920d53 100644 --- a/app/Service/UserServiceInterface.php +++ b/app/Service/UserServiceInterface.php @@ -24,6 +24,6 @@ interface UserServiceInterface * @param int $limit_amount * @return mixed */ - public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id); + public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id, $limit_amount = 3); } \ No newline at end of file From 6179e6e001b80f63e9267bc01ab74d66f433a0fc Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 21:18:29 +0800 Subject: [PATCH 164/172] =?UTF-8?q?=E6=89=93=E4=B8=AA=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/LogLabel.php | 5 +++++ app/Service/DeviceServiceImp.php | 3 +-- app/Service/MqttSpeakerService.php | 2 +- app/Service/OrderService.php | 16 ++++++++++++++++ 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/app/Constants/LogLabel.php b/app/Constants/LogLabel.php index aafacd8..1c88863 100644 --- a/app/Constants/LogLabel.php +++ b/app/Constants/LogLabel.php @@ -26,4 +26,9 @@ class LogLabel extends AbstractConstants * @Message("Pay Notice Log Label") */ const PAY_NOTIFY_WXMINI = 'notify_wxmini'; + + /** + * @Message("Order Log Label") + */ + const ORDER_LOG = 'order_log'; } diff --git a/app/Service/DeviceServiceImp.php b/app/Service/DeviceServiceImp.php index 16c9110..76a09e0 100644 --- a/app/Service/DeviceServiceImp.php +++ b/app/Service/DeviceServiceImp.php @@ -112,8 +112,7 @@ class DeviceServiceImp implements DeviceServiceInterface ->where(['store_id' => $order['store_id'], 'is_bind' => SpeakerDevic::IS_BIND_YES]) ->get() ->toArray(); - - $msg = "{\"msg\":\"到账".$order['money']."元\"}"; + $msg = $order['type']==1 ? "{\"msg\":\"您有新的外卖订单\"}" : "{\"msg\":\"到账".$order['money']."元\"}"; foreach ($device_names as $key => $dev_name) { $this->IOTService->pub($dev_name['device_name'], $msg); } diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index d058ae7..337834a 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -30,7 +30,7 @@ class MqttSpeakerService implements MqttServiceInterface // 循环发送 foreach ($orders as $k => &$order) { - $order['template'] = "懒族支付到账".floatval($order['money'])."元"; + $order['template'] = $order['type']==1 ? "您有新的外卖订单" : "到账".floatval($order['money'])."元"; // 获取终端ID $order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei'); // 发布订阅消息 diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index b637ac3..7511b79 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -2,6 +2,8 @@ namespace App\Service; +use App\Commons\Log; +use App\Constants\LogLabel; use App\Model\Coupon; use App\Model\CouponUserRec; use App\Model\CouponUserUse; @@ -19,6 +21,11 @@ use Hyperf\Di\Annotation\Inject; class OrderService implements OrderServiceInterface { + /** + * @Inject + * @var Log + */ + protected $log; /** * @Inject @@ -333,6 +340,11 @@ class OrderService implements OrderServiceInterface } catch (Exception $e) { + $this->log->event( + LogLabel::ORDER_LOG, + $e->getMessage() + ); + Db::rollBack(); return $e->getMessage(); @@ -444,6 +456,10 @@ class OrderService implements OrderServiceInterface Db::commit(); return $orderMainId; } catch (Exception $e) { + $this->log->event( + LogLabel::ORDER_LOG, + $e->getMessage() + ); Db::rollBack(); return '购买失败'; } From c65e432ec724b4d1845dd5d97081cbd90ad35d2e Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 21:21:18 +0800 Subject: [PATCH 165/172] =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/OrderService.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 7511b79..3eab4a9 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -342,7 +342,7 @@ class OrderService implements OrderServiceInterface $this->log->event( LogLabel::ORDER_LOG, - $e->getMessage() + ['message' => $e->getMessage()] ); Db::rollBack(); @@ -458,7 +458,7 @@ class OrderService implements OrderServiceInterface } catch (Exception $e) { $this->log->event( LogLabel::ORDER_LOG, - $e->getMessage() + ['message' => $e->getMessage()] ); Db::rollBack(); return '购买失败'; From 4f07a7424d87c8a9cc408a5c7289b2260b771c0a Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 21:37:59 +0800 Subject: [PATCH 166/172] =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 33 ++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 9f47c82..b58bc91 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -177,14 +177,27 @@ class NotifyController extends BaseController // 喇叭通知,兼容旧音响,MQTT+IOT $res = $this->mqttSpeakerService->speakToStore($orderMain->id); + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + ['fail_mqtt' => json_encode($res)] + ); $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); - + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + ['fail_device' => json_encode($res)] + ); // 公众号模板消息 $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); - + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + ['fail_mini' => json_encode($res)] + ); // 打印订单,自动打印 TODO 后续优化调用逻辑 $res = $this->feiePrintService->feiePrint($orderMain->global_order_id); - + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + ['fail_feie' => json_encode($res)] + ); Db::commit(); return true; @@ -352,11 +365,21 @@ class NotifyController extends BaseController // 喇叭通知,兼容旧音响,MQTT+IOT $res = $this->mqttSpeakerService->speakToStore($orderMain->id); + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + ['fail_mqtt' => json_encode($res)] + ); $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); - + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + ['fail_device' => json_encode($res)] + ); // 公众号模板消息 $res = $this->miniprogramService->sendTemMsgForOfflineOrder($orderMain->id); - + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + ['fail_mini' => json_encode($res)] + ); Db::commit(); return true; From d07a2eaf30f9aa6c5597ef600282bf557239c901 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 22:07:16 +0800 Subject: [PATCH 167/172] Fixbug --- app/Model/Store.php | 1 + config/autoload/middlewares.php | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Model/Store.php b/app/Model/Store.php index db4805a..72c42de 100644 --- a/app/Model/Store.php +++ b/app/Model/Store.php @@ -5,5 +5,6 @@ namespace App\Model; class Store extends Model { protected $table = 'ims_cjdc_store'; + public $timestamps = false; } \ No newline at end of file diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index fa4a0fc..4841754 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -11,7 +11,6 @@ declare(strict_types=1); */ return [ 'http' => [ - // \App\Middleware\Auth\ApiMiddleware::class, \App\Middleware\CorsMiddleware::class, \Hyperf\Validation\Middleware\ValidationMiddleware::class, ], From afc653445a2586ccb19d12c63ef35c143adfd0f0 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 22:08:59 +0800 Subject: [PATCH 168/172] F --- config/autoload/middlewares.php | 1 + 1 file changed, 1 insertion(+) diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index 4841754..b8c0296 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -13,5 +13,6 @@ return [ 'http' => [ \App\Middleware\CorsMiddleware::class, \Hyperf\Validation\Middleware\ValidationMiddleware::class, + ], ]; From b3d1b14c563bd3777549d95c5400f628a7491a17 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 22:09:32 +0800 Subject: [PATCH 169/172] Fix middle --- config/autoload/middlewares.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index 9f57500..4841754 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -12,8 +12,6 @@ declare(strict_types=1); return [ 'http' => [ \App\Middleware\CorsMiddleware::class, - \App\Middleware\Auth\ApiMiddleware::class, \Hyperf\Validation\Middleware\ValidationMiddleware::class, - ], ]; From de784c32c3c32b1d4c001ac34860756ad628c0b9 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 22:30:16 +0800 Subject: [PATCH 170/172] Fix cash --- app/Controller/PaymentController.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index 9fc92ae..b2c6fba 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -33,8 +33,7 @@ class PaymentController extends BaseController $result = $app->order->unify([ 'body' => '懒族生活 - 外卖下单', 'out_trade_no' => $orderMain->global_order_id, - // 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), - 'total_fee' => 1, + 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), 'notify_url' => config('site_host') . '/wechat/notify/wxminionline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], From ac4ff48e1758cd14103a619c25d7e51efe2b6952 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 22:49:50 +0800 Subject: [PATCH 171/172] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E8=BF=94?= =?UTF-8?q?=E5=88=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 10 + app/Service/CouponRebateService.php | 531 +++++++++++++++++++ app/Service/CouponRebateServiceInterface.php | 24 + config/autoload/dependencies.php | 1 + 4 files changed, 566 insertions(+) create mode 100644 app/Service/CouponRebateService.php create mode 100644 app/Service/CouponRebateServiceInterface.php diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index b58bc91..955db3f 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -13,6 +13,7 @@ use App\Model\Store; use App\Model\StoreAccount; use App\Model\SystemConfig; use App\Model\Users; +use App\Service\CouponRebateServiceInterface; use App\Service\DeviceServiceInterface; use App\Service\FeiePrintServiceInterface; use App\Service\MiniprogramServiceInterface; @@ -61,6 +62,12 @@ class NotifyController extends BaseController */ protected $userService; + /** + * @Inject + * @var CouponRebateServiceInterface + */ + protected $couponRebateService; + public function wxminiOnline() { @@ -175,6 +182,9 @@ class NotifyController extends BaseController $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics); } + // 优惠券返券 + $this->couponRebateService->couponRebateInTask($orderMain->id); + // 喇叭通知,兼容旧音响,MQTT+IOT $res = $this->mqttSpeakerService->speakToStore($orderMain->id); $this->log->event( diff --git a/app/Service/CouponRebateService.php b/app/Service/CouponRebateService.php new file mode 100644 index 0000000..efe3f34 --- /dev/null +++ b/app/Service/CouponRebateService.php @@ -0,0 +1,531 @@ +0领取失败 + $result = [ + 'status' => 1, + 'coupon_text' => '活动已过期~' + ]; + /* 如果请求的优惠券ids为空,则返回过期提示 */ + if($this->commonService->empty($params["ids"])){ + return $result; + } + + $ids = $params["ids"]; + $idsData = is_array($ids) ? $ids : explode(',',$ids); + + // 错误日志记录 + $errorData = [ + 'coupon_ids' =>$ids, + 'user_id' =>$userId, + 'receiveType' =>$receiveType, + 'sendUserId' =>$sendUserId, + 'phone' =>$phone + ]; + + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $activity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY ,'activity'); + // ssdb 键值 + $ssdbKey = 'activity_'.$activity.'_user_'.$userId; + $receiveSsdb = []; + + // 判断是否已全部领取过 + $userReceive = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE,$ssdbKey); + if($userReceive === false){ + $ids = $idsData; + }else{ + $userReceiveCouponIds = empty($userReceive) ? [] : explode(',',$userReceive) ; + $ids = array_diff($idsData, $userReceiveCouponIds); + $receiveSsdb = $userReceiveCouponIds; + } + + if(count($ids) > 0){ + try{ + Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,&$result,&$errorData,&$receiveSsdb) { + + $now = time(); + $success = []; + + //获取优惠券信息 (读写锁,完全控制,性能低) + $coupons = Coupon::whereIn('id', $ids)->lockForUpdate() + ->where('active_type',2) + ->where('status',1) + ->where('start_time', '<=', $now) + ->where('end_time', '>=', $now) + ->whereRaw('inventory > inventory_use') + ->select('id','title','inventory','inventory_use','full_amount','discounts','active_type') + ->get(); + + foreach($coupons as $coupon){ + $errorData['coupon_id'] = $coupon->id; + + // 查询一次能领取的数量 + $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number'); + if (env('SUB_CHANNEL') == 1) { + $couponReceiveType->where('receive_type',$receiveType); + } + $couponReceiveType = $couponReceiveType->first(); + + // 优惠券可领取数量 >= 本次领取数量 + if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){ + + // 判断是否领取过 存在记录则领取过 + $isReceive = CouponRec::select('id') + ->where('system_coupon_user_id',$coupon->id) + ->where('user_id',$userId) + ->exists(); + + if(!$isReceive){ + //记录已领取的数量 + $coupon->inventory_use += $couponReceiveType->one_receive_number; + + $couponReceive = new CouponRec; + $couponReceive->user_id = $userId; + $couponReceive->system_coupon_user_id = $coupon->id; + $couponReceive->order_main_id = 0; + $couponReceive->receive_time = $now; + $couponReceive->number = $couponReceiveType->one_receive_number; + $couponReceive->number_remain = $couponReceiveType->one_receive_number; + $couponReceive->status = 0; + $couponReceive->update_time = $now; + $couponReceive->receive_type = $receiveType; + $couponReceive->send_user_id = $sendUserId; + $couponReceive->phone = $phone; + + if ( $couponReceive->save() && $coupon->save() ) { + $success[] = $coupon; + $receiveSsdb[] = $coupon->id; + }else{ + $errorData['msg'] = '添加优惠券到用户领取表或者记录已领取数量失败'; + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + } + } + } + } + if(count($success) > 0){ + $result['status'] = 0; + $result['coupon_text'] = '恭喜您领取成功!'; + } + }); + } catch (Exception $e){ + $errorData['msg'] = $e->getMessage(); + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + } + + if(count($receiveSsdb) > 0){ + + $saveSsdb = [ + $ssdbKey, + implode(',',$receiveSsdb) + ]; + if(false === $ssdb->exec('hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $saveSsdb)){ + $errorData['msg'] = '记录领取优惠券到ssdb失败'; + $this->log->event( + LogLabel::COUPON_LOG, + $errorData + ); + }; + } + }else{ + $result['status'] = 2; + $result['coupon_text'] = '您已领取!赶快去下单吧~'; + } + + return $result; + } + + /* + * 判断用户是否已领取过优惠券 + * */ + public function isCouponRebate($user_id) + { + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $activity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY ,'activity'); + // ssdb 键值 + $ssdbKey = 'activity_'.$activity.'_user_'.$user_id; + + // 判断是否已全部领取过 + $userReceive = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE,$ssdbKey); + if($userReceive === false || is_null($userReceive)){ + return false; + }else{ + return $userReceive; + } + + } + + /* + *获取活动信息 + */ + public function getActiveInfo() + { + //获取SSDB上的活动信息 + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); + $coupon_ids = explode(',',$active['forward']); + $time = time(); + $res = Db::table('ims_system_coupon_user') + ->whereIn('id',$coupon_ids) + ->where([ + ['status', '=', 1], + ['active_type', '=', 2], + ['start_time', '<=', $time], + ['end_time', '>', $time], + ]) + ->whereRaw('inventory > inventory_use') + ->orderBy('weigh', 'desc') + ->orderBy('addtime', 'desc') + ->get(); + return $res; + } + + /** + * 将优惠券绑定活动 + * 领取优惠券 COUPON_REBATE_FORWARD 可多张 + * 返还优惠券 COUPON_REBATE_REPAY 只一张 + */ + public function tieCouponActive($couponActivity, $couponForward, $couponRepay) + { + + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + + $data = [ + 'activity', $couponActivity, + 'forward' , $couponForward, + 'repay' , $couponRepay + ]; + + $result = [ + 'result' => ($ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $data) === false) ? false : true , + 'data' => $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY) + ]; + + return $result; + } + + /* + * 支付成功 返券 + */ + public function couponRebate($order_id) + { + //获取SSDB上的活动信息 + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $active = $ssdb->execWithoutTask('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); + //判断返券优惠券是否有库存 + $inventory = Db::table('ims_system_coupon_user') + ->where('id',$active['repay']) + ->whereRaw('inventory > inventory_use') + ->exists(); + if(!$inventory){ + //库存不足 + return false; + } + + //获取活动发放优惠券id + $coupon_ids = explode(',',$active['forward']); + + /* 判断被使用的优惠券类型是否为转发活动优惠券 */ + $coupon = Db::table('ims_system_coupon_user_receive as r') + ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id') + ->where([ + ['u.order_main_id', '=', $order_id], + ['r.send_user_id', '>', 0], + ['r.rebate_type', '=', 1], + ['r.receive_type', '=', 4], + ]) + ->whereIn('r.system_coupon_user_id',$coupon_ids) + ->select('r.user_id', 'r.send_user_id') + ->first(); + /* 如果使用的优惠券为转发活动优惠券 + **则给赠送者返一张优惠券 + * **自己给自己转发的券不给返券 + */ + if ($coupon && ($coupon->user_id != $coupon->send_user_id)) { + //是否已返过券 + $exists_coupon_rebate = Db::table('ims_system_coupon_user_receive') + ->where([ + ['system_coupon_user_id' ,'=', $active['repay']], + ['user_id' ,'=', $coupon->send_user_id], + ['receive_type' ,'=', 5], + ]) + ->select('id','status') + ->first(); + //开启事务 + Db::beginTransaction(); + try { + //返券 + if($exists_coupon_rebate){ + //如果已有该优惠券 则领取数量 和 可用数量 自增1 + Db::table('ims_system_coupon_user_receive') + ->where([ + ['id' ,'=', $exists_coupon_rebate->id], + ]) + ->increment('number'); + Db::table('ims_system_coupon_user_receive') + ->where([ + ['id' ,'=', $exists_coupon_rebate->id], + ]) + ->increment('number_remain'); + //如果该用户在领取表中 status为已用完状态 2 则改为已用部分 1 + if($exists_coupon_rebate->status == 2){ + Db::table('ims_system_coupon_user_receive') + ->where([ + ['id' ,'=', $exists_coupon_rebate->id], + ]) + ->update(['status' => 1]);; + } + }else { + //否则新增一条返券记录 + $nowTime = time(); + Db::table('ims_system_coupon_user_receive')->insert([ + [ + 'user_id' => $coupon->send_user_id, + 'system_coupon_user_id' => $active['repay'], + 'receive_type' => 5, + 'status' => 0, + 'number' => 1, + 'number_remain' => 1, + 'order_main_id' => $order_id, + 'receive_time' => $nowTime, + 'update_time' => $nowTime, + 'created_at' => $nowTime, + 'updated_at' => $nowTime, + ] + ]); + } + //首次返券更新rebate_type字段 防止重复返券 + Db::table('ims_system_coupon_user_receive') + ->where([ + ['user_id','=',$coupon->user_id], + ['receive_type','=',4], + ]) + ->whereIn('system_coupon_user_id',$coupon_ids) + ->update(['rebate_type' => 2]); + //更新库存操作 + Db::table('ims_system_coupon_user') + ->where('id', $active['repay']) + ->increment('inventory_use'); + + //添加领取记录到ssdb + $data = [ + $order_id,$coupon->user_id, + ]; + $ssdb->execWithoutTask('multi_hset', SsdbKeysPrefix::COUPON_REBATE_LIST.$coupon->send_user_id, $data); + // 提交 + Db::commit(); + } catch (\Exception $e) { + //写入日志文件 + $log_Data = array(); + $log_Data['name'] = '返券'; + $log_Data['order_id'] = $order_id; + $log_Data['msg'] = '返券失败'; + $this->log->event( + LogLabel::COUPON_LOG, + $log_Data + ); + // 回滚 + Db::rollBack(); + } + } + return true; + } + + /* + * 支付成功 返券 + */ + public function couponRebateInTask($order_id) + { + //获取SSDB上的活动信息 + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY); + //判断返券优惠券是否有库存 + $inventory = Db::table('ims_system_coupon_user') + ->where('id',$active['repay']) + ->whereRaw('inventory > inventory_use') + ->exists(); + if(!$inventory){ + //库存不足 + return false; + } + + //获取活动发放优惠券id + $coupon_ids = explode(',',$active['forward']); + + /* 判断被使用的优惠券类型是否为转发活动优惠券 */ + $coupon = Db::table('ims_system_coupon_user_receive as r') + ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id') + ->where([ + ['u.order_main_id', '=', $order_id], + ['r.send_user_id', '>', 0], + ['r.rebate_type', '=', 1], + ['r.receive_type', '=', 4], + ]) + ->whereIn('r.system_coupon_user_id',$coupon_ids) + ->select('r.user_id', 'r.send_user_id') + ->first(); + /* 如果使用的优惠券为转发活动优惠券 + **则给赠送者返一张优惠券 + * **自己给自己转发的券不给返券 + */ + if ($coupon && ($coupon->user_id != $coupon->send_user_id)) { + //是否已返过券 + $exists_coupon_rebate = Db::table('ims_system_coupon_user_receive') + ->where([ + ['system_coupon_user_id' ,'=', $active['repay']], + ['user_id' ,'=', $coupon->send_user_id], + ['receive_type' ,'=', 5], + ]) + ->select('id','status') + ->first(); + //开启事务 + Db::beginTransaction(); + try { + //返券 + if($exists_coupon_rebate){ + //如果已有该优惠券 则领取数量 和 可用数量 自增1 + Db::table('ims_system_coupon_user_receive') + ->where([ + ['id' ,'=', $exists_coupon_rebate->id], + ]) + ->increment('number'); + Db::table('ims_system_coupon_user_receive') + ->where([ + ['id' ,'=', $exists_coupon_rebate->id], + ]) + ->increment('number_remain'); + //如果该用户在领取表中 status为已用完状态 2 则改为已用部分 1 + if($exists_coupon_rebate->status == 2){ + Db::table('ims_system_coupon_user_receive') + ->where([ + ['id' ,'=', $exists_coupon_rebate->id], + ]) + ->update(['status' => 1]);; + } + }else { + //否则新增一条返券记录 + $nowTime = time(); + Db::table('ims_system_coupon_user_receive')->insert([ + [ + 'user_id' => $coupon->send_user_id, + 'system_coupon_user_id' => $active['repay'], + 'receive_type' => 5, + 'status' => 0, + 'number' => 1, + 'number_remain' => 1, + 'order_main_id' => $order_id, + 'receive_time' => $nowTime, + 'update_time' => $nowTime, + 'created_at' => $nowTime, + 'updated_at' => $nowTime, + ] + ]); + } + //首次返券更新rebate_type字段 防止重复返券 + Db::table('ims_system_coupon_user_receive') + ->where([ + ['user_id','=',$coupon->user_id], + ['receive_type','=',4], + ]) + ->whereIn('system_coupon_user_id',$coupon_ids) + ->update(['rebate_type' => 2]); + //更新库存操作 + Db::table('ims_system_coupon_user') + ->where('id', $active['repay']) + ->increment('inventory_use'); + + //添加领取记录到ssdb + $data = [ + $order_id,$coupon->user_id, + ]; + $ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_LIST.$coupon->send_user_id, $data); + // 提交 + Db::commit(); + } catch (\Exception $e) { + //写入日志文件 + $log_Data = array(); + $log_Data['name'] = '返券'; + $log_Data['order_id'] = $order_id; + $log_Data['msg'] = '返券失败'; + $this->log->event( + LogLabel::COUPON_LOG, + $log_Data + ); + // 回滚 + Db::rollBack(); + } + } + return true; + } + + /** + * 清优惠券领取记录(SSDB) + */ + public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0, $isAll = 0){ + $key = 'activity_'.$activity.'_user_'.$userId; + $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); + + if($isAll > 0){ + if($get > 0){ + return $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE); + }else{ + return ( $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE) === false) ? false : true ; + } + }else { + if($get > 0){ + return $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key); + }else{ + return ( $ssdb->exec('hdel', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key) === false) ? false : true ; + } + } + } +} \ No newline at end of file diff --git a/app/Service/CouponRebateServiceInterface.php b/app/Service/CouponRebateServiceInterface.php new file mode 100644 index 0000000..4208c28 --- /dev/null +++ b/app/Service/CouponRebateServiceInterface.php @@ -0,0 +1,24 @@ + \App\Service\FeiePrintService::class, \App\Service\MiniprogramServiceInterface::class => \App\Service\MiniprogramService::class, \App\Service\UserServiceInterface::class => \App\Service\UserService::class, + \App\Service\CouponRebateServiceInterface::class => \App\Service\CouponRebateService::class, ]; From 963da8e8d5d42f50ed61c9d8ecee2e23db72e937 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 20 Aug 2020 17:11:13 +0800 Subject: [PATCH 172/172] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=AF=AD=E9=9F=B3?= =?UTF-8?q?=E6=92=AD=E6=8A=A5=E5=86=85=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/DeviceServiceImp.php | 2 +- app/Service/MqttSpeakerService.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Service/DeviceServiceImp.php b/app/Service/DeviceServiceImp.php index 76a09e0..852a88f 100644 --- a/app/Service/DeviceServiceImp.php +++ b/app/Service/DeviceServiceImp.php @@ -112,7 +112,7 @@ class DeviceServiceImp implements DeviceServiceInterface ->where(['store_id' => $order['store_id'], 'is_bind' => SpeakerDevic::IS_BIND_YES]) ->get() ->toArray(); - $msg = $order['type']==1 ? "{\"msg\":\"您有新的外卖订单\"}" : "{\"msg\":\"到账".$order['money']."元\"}"; + $msg = $order['type']==1 ? "{\"msg\":\"您有新的懒族外卖订单\"}" : "{\"msg\":\"微信到账".$order['money']."元\"}"; foreach ($device_names as $key => $dev_name) { $this->IOTService->pub($dev_name['device_name'], $msg); } diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index 337834a..07a6c08 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -30,7 +30,7 @@ class MqttSpeakerService implements MqttServiceInterface // 循环发送 foreach ($orders as $k => &$order) { - $order['template'] = $order['type']==1 ? "您有新的外卖订单" : "到账".floatval($order['money'])."元"; + $order['template'] = $order['type']==1 ? "您有新的懒族外卖订单" : "微信到账".floatval($order['money'])."元"; // 获取终端ID $order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei'); // 发布订阅消息