Commit d0e61f2b authored by root's avatar root

hyperf2.2.0

parent 67b1274b
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
# Meibuyu Library # Meibuyu Library
美不语微服务官方接口库 美不语微服务官方接口库
### 1、如何使用 ### 1、如何使用
在使用的项目下的composer.json 加入以下内容 在使用的项目下的composer.json 加入以下内容
``` ```
"repositories": { "repositories": {
"meibuyu/micro": { "meibuyu/micro": {
"type": "path", "type": "path",
"url": "path/to/micro",//本库的具体地址,随意找个地方git clone下来 "url": "path/to/micro",//本库的具体地址,随意找个地方git clone下来
"options": { "options": {
"symlink": true "symlink": true
} }
}, },
} }
``` ```
然后在使用的项目下执行 然后在使用的项目下执行
``` ```
composer require meibuyu/micro @dev composer require meibuyu/micro @dev
``` ```
--- ---
### 2、鉴权注解使用方法 ### 2、鉴权注解使用方法
> 使用时必须接入用户服务 > 使用时必须接入用户服务
> 权限名会拼接env文件中的APP_NAME属性,请注意唯一性 > 权限名会拼接env文件中的APP_NAME属性,请注意唯一性
> 所有权限必须存在于用户服务的权限表中,若不存在,请联系管理员添加权限 > 所有权限必须存在于用户服务的权限表中,若不存在,请联系管理员添加权限
##### 1、@AutoPerm ##### 1、@AutoPerm
在控制器头部添加@AutoPerm注解,为该控制器下所有的方法添加鉴权功能,生成的权限名为`蛇形控制名_蛇形方法名` 在控制器头部添加@AutoPerm注解,为该控制器下所有的方法添加鉴权功能,生成的权限名为`蛇形控制名_蛇形方法名`
``` ```
/** /**
* @AutoPerm() * @AutoPerm()
*/ */
class UserInfoController {} class UserInfoController {}
``` ```
参数: 参数:
> 1. prefix, 前缀(字符串),默认为蛇形控制名(user_info) > 1. prefix, 前缀(字符串),默认为蛇形控制名(user_info)
> 2. exclude, 要排除的方法名(字符串数组),默认为空 > 2. exclude, 要排除的方法名(字符串数组),默认为空
``` ```
/** /**
* @AutoPerm(prefix="user", exclude={"getUser"}) * @AutoPerm(prefix="user", exclude={"getUser"})
*/ */
class UserInfoController {} class UserInfoController {}
``` ```
##### 2、@Perm ##### 2、@Perm
在控制器中的方法头部添加@Perm注解,为当前方法添加鉴权功能,生成权限名为`蛇形控制名_蛇形方法名` 在控制器中的方法头部添加@Perm注解,为当前方法添加鉴权功能,生成权限名为`蛇形控制名_蛇形方法名`
``` ```
/** /**
* @Perm() * @Perm()
*/ */
function getUser {} function getUser {}
``` ```
参数: 参数:
> name, 前缀(字符串),默认为蛇形方法名(user) > name, 前缀(字符串),默认为蛇形方法名(user)
``` ```
/** /**
* @Perm("get_user") * @Perm("get_user")
*/ */
function getUser {} function getUser {}
``` ```
### 3、对集合获取值、然后调用rpc方法获取数据后,重新赋值 ### 3、对集合获取值、然后调用rpc方法获取数据后,重新赋值
#### 1)、获取值,设置值 #### 1)、获取值,设置值
``` ```
$list = Task::with(['c'=>function($q){ $list = Task::with(['c'=>function($q){
$q->select(['d','y']); $q->select(['d','y']);
}])->select(['c','v'])->->paginate(2); }])->select(['c','v'])->->paginate(2);
/* /*
* 假设拿到的数据是这个 * 假设拿到的数据是这个
* $list = [['c' => ['d' => 4, 'y' => 9], 'v' => '5'], ['c'=>'','v'=>'8'], ['c' => ['d' => 6, 'y' => 10], 'v' => '7']]; * $list = [['c' => ['d' => 4, 'y' => 9], 'v' => '5'], ['c'=>'','v'=>'8'], ['c' => ['d' => 6, 'y' => 10], 'v' => '7']];
*/ */
$user_ids = get_collection_values($list, 'c.d'); $user_ids = get_collection_values($list, 'c.d');
// 去RPC拿用户数据 // 去RPC拿用户数据
$users = $this->userService->getByIdList($hello); $users = $this->userService->getByIdList($hello);
//重新赋值给列表 //重新赋值给列表
put_collection_values($list, $users, 'c.d', 'user', 'id'); put_collection_values($list, $users, 'c.d', 'user', 'id');
/* /*
* 则新的数据如下 * 则新的数据如下
* $list = [['c' => ['d' => 4,'user'=>['id'=>4,'name'=>'张三'], 'y' => 9], 'v' => '5'], * $list = [['c' => ['d' => 4,'user'=>['id'=>4,'name'=>'张三'], 'y' => 9], 'v' => '5'],
['c'=>'','v'=>'8'], ['c'=>'','v'=>'8'],
['c' => ['d' => 6, ,'user'=>['id'=>6,'name'=>'王五']'y' => 10], 'v' => '7']]; ['c' => ['d' => 6, ,'user'=>['id'=>6,'name'=>'王五']'y' => 10], 'v' => '7']];
*/ */
``` ```
#### 2)、判断各种值和更新各种值 #### 2)、判断各种值和更新各种值
``` ```
// 使用第一步获取的列表 // 使用第一步获取的列表
// askModel文件 新增获取值,和设置值方法 // askModel文件 新增获取值,和设置值方法
* 动态判断 * 动态判断
* @param $currentUserId * @param $currentUserId
*/ */
public function getCanDelete($currentUserId) public function getCanDelete($currentUserId)
{ {
$this->attributes['can_delete'] = $this->user_id == $currentUserId ? true : false; $this->attributes['can_delete'] = $this->user_id == $currentUserId ? true : false;
} }
/**新增time_show属性 /**新增time_show属性
* @return string 返回友好时间值 * @return string 返回友好时间值
*/ */
public function getTimeShowAttribute() public function getTimeShowAttribute()
{ {
if ($this->status == 2) { if ($this->status == 2) {
return '已完成'; return '已完成';
} }
$time = time(); $time = time();
if ($this->status === 0) { if ($this->status === 0) {
$time = $time - strtotime($this->start_time); $time = $time - strtotime($this->start_time);
return human_time($time) . "后开始"; return human_time($time) . "后开始";
} }
if ($this->status === 1) { if ($this->status === 1) {
$time = $time - strtotime($this->end_time); $time = $time - strtotime($this->end_time);
if ($time > 0) { if ($time > 0) {
return "超时" . human_time($time); return "超时" . human_time($time);
} }
return human_time($time) . "后结束"; return human_time($time) . "后结束";
} }
} }
/** /**
* 设置结束时间 * 设置结束时间
* @param string $time * @param string $time
*/ */
public function setFinishAttribute($time = '') public function setFinishAttribute($time = '')
{ {
$this->attributes['finish'] = $time ? $time : today(); $this->attributes['finish'] = $time ? $time : today();
} }
// TaskRepositoryEloquent 文件 // TaskRepositoryEloquent 文件
// 获取列表方法 // 获取列表方法
.. ..... .. .....
$currentUserId = Auth::id(); $currentUserId = Auth::id();
foreach ($list->items() as $item) { foreach ($list->items() as $item) {
$item->getCanDelete($currentUserId);//结果会新增 can_delete属性 $item->getCanDelete($currentUserId);//结果会新增 can_delete属性
$item->time_show;//自动调用getTimeShowAttribute方法,并设置值 $item->time_show;//自动调用getTimeShowAttribute方法,并设置值
$item->finish=today();//自动调用setFinishAttribute方法,并设置值 $item->finish=today();//自动调用setFinishAttribute方法,并设置值
} }
return $list;//集合自动转数组,会带上新的三个属性,和分页数据 return $list;//集合自动转数组,会带上新的三个属性,和分页数据
``` ```
### 4、新方法说明 ### 4、新方法说明
#### 1)、human_time 友好的显示时间 #### 1)、human_time 友好的显示时间
用法: 用法:
``` ```
human_time(time()-strtotime('2020-06-06 12:12')); human_time(time()-strtotime('2020-06-06 12:12'));
//12分钟等等根据计算值自动显示时分秒,不足一分钟显示秒,不足一小时显示分 //12分钟等等根据计算值自动显示时分秒,不足一分钟显示秒,不足一小时显示分
//不足一天显示小时 //不足一天显示小时
//可以自行测试 //可以自行测试
``` ```
#### 2)、info 输出数据到控制台,支持任何数据,自动换行 方便测试 #### 2)、info 输出数据到控制台,支持任何数据,自动换行 方便测试
用法: 用法:
``` ```
//支持多参数 //支持多参数
info('aaa',[1,2,3],new stdClass(){$a=1;},collect([1,23,4])); info('aaa',[1,2,3],new stdClass(){$a=1;},collect([1,23,4]));
info(1); info(1);
``` ```
### 5、数据表批量操作 ### 5、数据表批量操作
用法: 用法:
继承 \Meibuyu\Micro\Model\BaseModel 的模型: 继承 \Meibuyu\Micro\Model\BaseModel 的模型:
``` ```
class LogTrace extends BaseModel class LogTrace extends BaseModel
{ {
protected $table = 'trace_logs'; protected $table = 'trace_logs';
/** /**
* 是否使用时间戳管理 * 是否使用时间戳管理
* @var bool * @var bool
*/ */
public $timestamps = false; public $timestamps = false;
/** /**
* 可写入数据的字段. * 可写入数据的字段.
* @var array * @var array
*/ */
protected $fillable = [ protected $fillable = [
'source', 'source',
'origin_params', 'origin_params',
'is_completed', 'is_completed',
'process_info', 'process_info',
]; ];
} }
``` ```
得到基于主键或唯一索引作为条件的俩个批处理方法: 得到基于主键或唯一索引作为条件的俩个批处理方法:
``` ```
//批量更新,、$data为二维数组,必须包含主键或唯一索引的数据 //批量更新,、$data为二维数组,必须包含主键或唯一索引的数据
//参数二缺省为主键名,或唯一索引名 //参数二缺省为主键名,或唯一索引名
LogTrace::getModel()->batchUpdateByField($data,'request_id') LogTrace::getModel()->batchUpdateByField($data,'request_id')
//基于ON DUPLICATE KEY UPDATE 批量更新或插入 $data 必须包含主键或唯一索引的数据 //基于ON DUPLICATE KEY UPDATE 批量更新或插入 $data 必须包含主键或唯一索引的数据
LogTrace::getModel()->batchUpdateOrCreateByUniqueKey($data); LogTrace::getModel()->batchUpdateOrCreateByUniqueKey($data);
``` ```
### 6、基于@LogTrace()注解,实现异步日志队列服务 ### 6、基于@LogTrace()注解,实现异步日志队列服务
用法: 用法:
#### 1)、建立日志跟踪表 #### 1)、建立日志跟踪表
```sql ```sql
CREATE TABLE `trace_logs` ( CREATE TABLE `trace_logs` (
`id` bigint(20) NOT NULL AUTO_INCREMENT, `id` bigint(20) NOT NULL AUTO_INCREMENT,
`request_id` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '一次http或rpc请求调用的唯一key', `request_id` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '一次http或rpc请求调用的唯一key',
`source` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '来源,包含调用类命名空间及方法', `source` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '来源,包含调用类命名空间及方法',
`origin_params` json NOT NULL COMMENT '记录注解方法被调用开始的原始传参', `origin_params` json NOT NULL COMMENT '记录注解方法被调用开始的原始传参',
`is_completed` tinyint(1) NOT NULL DEFAULT '0' COMMENT '此请求是否完成,使用LogTraceHandler::markComplete()标记', `is_completed` tinyint(1) NOT NULL DEFAULT '0' COMMENT '此请求是否完成,使用LogTraceHandler::markComplete()标记',
`process_info` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '执行过程中输出,使用LogTraceHandler::recordProcess()记录', `process_info` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '执行过程中输出,使用LogTraceHandler::recordProcess()记录',
`created_at` datetime NOT NULL COMMENT '日志记录开始时间', `created_at` datetime NOT NULL COMMENT '日志记录开始时间',
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
UNIQUE KEY `request_id` (`request_id`) UNIQUE KEY `request_id` (`request_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5868 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ) ENGINE=InnoDB AUTO_INCREMENT=5868 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
``` ```
#### 2)、定义消费进程,日志批量更新到数据库 #### 2)、定义消费进程,日志批量更新到数据库
```php ```php
<?php <?php
/** /**
* 异步日志队列批处理 * 异步日志队列批处理
*/ */
namespace App\Process; namespace App\Process;
use Hyperf\Process\AbstractProcess; use Hyperf\Process\AbstractProcess;
use Hyperf\Process\Annotation\Process; use Hyperf\Process\Annotation\Process;
use Meibuyu\Micro\Handler\LogTrace\LogTraceQueue; use Meibuyu\Micro\Handler\LogTrace\LogTraceQueue;
/** /**
* @Process(name="SyncTraceLog") * @Process(name="SyncTraceLog")
*/ */
class SyncTraceLog extends AbstractProcess class SyncTraceLog extends AbstractProcess
{ {
/** /**
* 进程数量 * 进程数量
* @var int * @var int
*/ */
public $nums = 1; public $nums = 1;
/** /**
* 进程名称 * 进程名称
* @var string * @var string
*/ */
public $name = 'syn-trace-log'; public $name = 'syn-trace-log';
/** /**
* 管道类型 * 管道类型
* @var int * @var int
*/ */
public $pipeType = 2; public $pipeType = 2;
/** /**
* 是否启用协程 * 是否启用协程
* @var bool * @var bool
*/ */
public $enableCoroutine = true; public $enableCoroutine = true;
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function handle(): void public function handle(): void
{ {
make(LogTraceQueue::class)->consume(); make(LogTraceQueue::class)->consume();
} }
} }
``` ```
#### 3)、对操作方法指定注解,主动记录日志信息 #### 3)、对操作方法指定注解,主动记录日志信息
``` ```
给test方法加上 @LogTrace() 注解,从此处开始记录日志,可在此请求的任何流程地方 给test方法加上 @LogTrace() 注解,从此处开始记录日志,可在此请求的任何流程地方
使用Meibuyu\Micro\Handler\LogTrace\LogTraceHandler::recordProcess 使用Meibuyu\Micro\Handler\LogTrace\LogTraceHandler::recordProcess
手动记录输出,下面只是最简单的示例 手动记录输出,下面只是最简单的示例
/** /**
* @LogTrace() * @LogTrace()
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
public function test() public function test()
{ {
try { try {
//记录数组 //记录数组
LogTraceHandler::recordProcess($this->request->all()); LogTraceHandler::recordProcess($this->request->all());
//流程1 //流程1
LogTraceHandler::recordProcess('执行到流程1'); LogTraceHandler::recordProcess('执行到流程1');
//流程2 //流程2
LogTraceHandler::recordProcess('执行到流程2'); LogTraceHandler::recordProcess('执行到流程2');
//流程3 抛出一个异常 //流程3 抛出一个异常
throw new Exception('test111'); throw new Exception('test111');
//流程执行完成标记结束 //流程执行完成标记结束
LogTraceHandler::markComplete(); LogTraceHandler::markComplete();
}catch (\Throwable $exception){ }catch (\Throwable $exception){
//记录异常日志 //记录异常日志
LogTraceHandler::recordProcess($exception); LogTraceHandler::recordProcess($exception);
} }
return 'test222'; return 'test222';
} }
##执行过程输出到 trace_logs表 process_info: ##执行过程输出到 trace_logs表 process_info:
array ( array (
'scanNo' => 'SPUS-20211202-158-3', 'scanNo' => 'SPUS-20211202-158-3',
) )
执行到流程1 执行到流程1
执行到流程2 执行到流程2
抛出一个异常 抛出一个异常
/var/www/runtime/container/proxy/App_Controller_IndexController.proxy.php line:80 /var/www/runtime/container/proxy/App_Controller_IndexController.proxy.php line:80
#0 /var/www/vendor/hyperf/di/src/Aop/ProceedingJoinPoint.php(84): App\Controller\IndexController->App\Controller\{closure}() #0 /var/www/vendor/hyperf/di/src/Aop/ProceedingJoinPoint.php(84): App\Controller\IndexController->App\Controller\{closure}()
#1 /var/www/vendor/hyperf/di/src/Aop/ProxyTrait.php(85): Hyperf\Di\Aop\ProceedingJoinPoint->processOriginalMethod() #1 /var/www/vendor/hyperf/di/src/Aop/ProxyTrait.php(85): Hyperf\Di\Aop\ProceedingJoinPoint->processOriginalMethod()
#2 /var/www/vendor/hyperf/utils/src/Pipeline.php(104): App\Controller\IndexController::Hyperf\Di\Aop\{closure}() #2 /var/www/vendor/hyperf/utils/src/Pipeline.php(104): App\Controller\IndexController::Hyperf\Di\Aop\{closure}()
#3 /var/www/vendor/hyperf/di/src/Aop/ProceedingJoinPoint.php(69): Hyperf\Utils\Pipeline::Hyperf\Utils\{closure}() #3 /var/www/vendor/hyperf/di/src/Aop/ProceedingJoinPoint.php(69): Hyperf\Utils\Pipeline::Hyperf\Utils\{closure}()
#4 /var/www/vendor/meibuyu/micro/src/Aspect/LogTraceAspect.php(32): Hyperf\Di\Aop\ProceedingJoinPoint->process() #4 /var/www/vendor/meibuyu/micro/src/Aspect/LogTraceAspect.php(32): Hyperf\Di\Aop\ProceedingJoinPoint->process()
#5 /var/www/vendor/hyperf/di/src/Aop/Pipeline.php(30): Meibuyu\Micro\Aspect\LogTraceAspect->process() #5 /var/www/vendor/hyperf/di/src/Aop/Pipeline.php(30): Meibuyu\Micro\Aspect\LogTraceAspect->process()
#6 /var/www/vendor/hyperf/utils/src/Pipeline.php(95): Hyperf\Di\Aop\Pipeline->Hyperf\Di\Aop\{closure}() #6 /var/www/vendor/hyperf/utils/src/Pipeline.php(95): Hyperf\Di\Aop\Pipeline->Hyperf\Di\Aop\{closure}()
#7 /var/www/vendor/hyperf/di/src/Aop/ProxyTrait.php(86): Hyperf\Utils\Pipeline->then() #7 /var/www/vendor/hyperf/di/src/Aop/ProxyTrait.php(86): Hyperf\Utils\Pipeline->then()
#8 /var/www/vendor/hyperf/di/src/Aop/ProxyTrait.php(29): App\Controller\IndexController::handleAround() #8 /var/www/vendor/hyperf/di/src/Aop/ProxyTrait.php(29): App\Controller\IndexController::handleAround()
#9 /var/www/runtime/container/proxy/App_Controller_IndexController.proxy.php(88): App\Controller\IndexController::__proxyCall() #9 /var/www/runtime/container/proxy/App_Controller_IndexController.proxy.php(88): App\Controller\IndexController::__proxyCall()
#10 /var/www/vendor/hyperf/http-server/src/CoreMiddleware.php(161): App\Controller\IndexController->test1() #10 /var/www/vendor/hyperf/http-server/src/CoreMiddleware.php(161): App\Controller\IndexController->test1()
#11 /var/www/vendor/hyperf/http-server/src/CoreMiddleware.php(113): Hyperf\HttpServer\CoreMiddleware->handleFound() #11 /var/www/vendor/hyperf/http-server/src/CoreMiddleware.php(113): Hyperf\HttpServer\CoreMiddleware->handleFound()
#12 /var/www/vendor/hyperf/dispatcher/src/AbstractRequestHandler.php(64): Hyperf\HttpServer\CoreMiddleware->process() #12 /var/www/vendor/hyperf/dispatcher/src/AbstractRequestHandler.php(64): Hyperf\HttpServer\CoreMiddleware->process()
#13 /var/www/vendor/hyperf/dispatcher/src/HttpRequestHandler.php(26): Hyperf\Dispatcher\AbstractRequestHandler->handleRequest() #13 /var/www/vendor/hyperf/dispatcher/src/HttpRequestHandler.php(26): Hyperf\Dispatcher\AbstractRequestHandler->handleRequest()
#14 /var/www/vendor/hyperf/dispatcher/src/HttpDispatcher.php(40): Hyperf\Dispatcher\HttpRequestHandler->handle() #14 /var/www/vendor/hyperf/dispatcher/src/HttpDispatcher.php(40): Hyperf\Dispatcher\HttpRequestHandler->handle()
#15 /var/www/vendor/hyperf/http-server/src/Server.php(116): Hyperf\Dispatcher\HttpDispatcher->dispatch() #15 /var/www/vendor/hyperf/http-server/src/Server.php(116): Hyperf\Dispatcher\HttpDispatcher->dispatch()
#16 {main} #16 {main}
返回结果:"test222" 返回结果:"test222"
``` ```
####使用说明 ####使用说明
> 1. 对方法加上 @LogTrace() 注解,建议注解的地方为http请求和rpc调用的入口处,便于使用脚本拿到原始传参便捷发起重试 > 1. 对方法加上 @LogTrace() 注解,建议注解的地方为http请求和rpc调用的入口处,便于使用脚本拿到原始传参便捷发起重试
> 2. 使用@LogTrace()注解的方法逻辑内任意地方使用LogTraceHandler::recordProcess记录输出(如须异步协程里也跟踪,第二参数须为true) > 2. 使用@LogTrace()注解的方法逻辑内任意地方使用LogTraceHandler::recordProcess记录输出(如须异步协程里也跟踪,第二参数须为true)
> 3. 日志跟踪数据都存放在trace_logs表,每一次请求或rpc调用都对应一条唯一记录,process_info字段按顺序记录了流程输出 > 3. 日志跟踪数据都存放在trace_logs表,每一次请求或rpc调用都对应一条唯一记录,process_info字段按顺序记录了流程输出
### 7、基于@AsyncCoroutine()注解,对方法实现异步协程处理 ### 7、基于@AsyncCoroutine()注解,对方法实现异步协程处理
对于耗时长,加快影响效率,可以使用写队列,消费处理。 对于耗时长,加快影响效率,可以使用写队列,消费处理。
也可以将这部分逻辑放到异步协程去处理,用法: 也可以将这部分逻辑放到异步协程去处理,用法:
``` ```
http 请求test1,调用 延迟5s的continueTest(该方法已加入AsyncCoroutine注解), http 请求test1,调用 延迟5s的continueTest(该方法已加入AsyncCoroutine注解),
但接口马上返回结果。5s后,后台将continueTest方法逻辑执行输出到控制台或者写入日志 但接口马上返回结果。5s后,后台将continueTest方法逻辑执行输出到控制台或者写入日志
/** /**
* @LogTrace() * @LogTrace()
* @return array * @return array
* @throws \Exception * @throws \Exception
*/ */
public function test1() public function test1()
{ {
//此处调用异步协程去处理,立刻返回结果 //此处调用异步协程去处理,立刻返回结果
$this->continueTest($this->request->all()); $this->continueTest($this->request->all());
return Coroutine::id(); return Coroutine::id();
} }
/** /**
* 使用AsyncCoroutine注解,使该方法投递到子协程里执行 * 使用AsyncCoroutine注解,使该方法投递到子协程里执行
* @AsyncCoroutine() * @AsyncCoroutine()
*/ */
private function continueTest($params) private function continueTest($params)
{ {
sleep(5); //睡眠5s sleep(5); //睡眠5s
LogTraceHandler::recordProcess(Coroutine::id(),true); LogTraceHandler::recordProcess(Coroutine::id(),true);
LogTraceHandler::recordProcess(Coroutine::parentId(),true); LogTraceHandler::recordProcess(Coroutine::parentId(),true);
return Coroutine::id(); return Coroutine::id();
} }
``` ```
##### 使用须知 ##### 使用须知
``` ```
1. 给某个方法加上异步协程AsyncCoroutine注解,该方法被投放到另一个协程执行, 1. 给某个方法加上异步协程AsyncCoroutine注解,该方法被投放到另一个协程执行,
该方法的传参尽量不要使用模型对象(等连接资源对象),如果使用模型对象投递到 该方法的传参尽量不要使用模型对象(等连接资源对象),如果使用模型对象投递到
另一个协程,进行更新操作,会造成数据错乱。如要使用应禁止更新等操作 另一个协程,进行更新操作,会造成数据错乱。如要使用应禁止更新等操作
2. 配合基于@LogTrace()注解异步日志队列服务,可以使用 LogTraceHandler::recordProcess 2. 配合基于@LogTrace()注解异步日志队列服务,可以使用 LogTraceHandler::recordProcess
对异步协程执行的情况进行跟踪,但在异步协程里,第二个参数必须为true 对异步协程执行的情况进行跟踪,但在异步协程里,第二个参数必须为true
如 LogTraceHandler::recordProcess('记录输出数据',true); 如 LogTraceHandler::recordProcess('记录输出数据',true);
``` ```
\ No newline at end of file
{ {
"name": "meibuyu/micro", "name": "meibuyu/micro",
"description": "美不语微服务公共接口库", "description": "美不语微服务公共接口库",
"type": "library", "type": "library",
"license": "MIT", "license": "MIT",
"authors": [ "authors": [
{ {
"name": "梁俊杰", "name": "梁俊杰",
"email": "blithe8787@163.com" "email": "blithe8787@163.com"
} }
], ],
"require": { "require": {
"ext-json": "*", "ext-json": "*",
"ext-redis": "*", "ext-redis": "*",
"ext-gd": "*", "ext-gd": "*",
"ext-curl": "*", "ext-curl": "*",
"ext-mbstring": "*", "ext-mbstring": "*",
"hyperf/cache": "~2.1.0", "hyperf/cache": "~2.2.0",
"hyperf/framework": "~2.1.0", "hyperf/framework": "~2.2.0",
"hyperf/db-connection": "~2.1.0", "hyperf/db-connection": "~2.2.0",
"hyperf/validation": "~2.1.0", "hyperf/validation": "~2.2.0",
"hyperf/command": "~2.1.0", "hyperf/command": "~2.2.0",
"hyperf/redis": "~2.1.0", "hyperf/redis": "~2.2.0",
"hyperf/guzzle": "~2.1.0", "hyperf/guzzle": "~2.2.0",
"hyperf/config": "~2.1.0", "hyperf/config": "~2.2.0",
"hyperf/logger": "~2.1.0", "hyperf/logger": "~2.2.0",
"hyperf/service-governance": "~2.1.0", "hyperf/service-governance": "~2.2.0",
"fzaninotto/faker": "^1.9", "fzaninotto/faker": "^1.9",
"phpoffice/phpspreadsheet": "^1.18", "phpoffice/phpspreadsheet": "^1.18",
"dimsav/unix-zipper": "1.*", "dimsav/unix-zipper": "1.*",
"hyperf/amqp": "~2.1.0", "hyperf/amqp": "~2.2.0",
"hyperf/paginator": "~2.1.0" "hyperf/paginator": "~2.2.0"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"Meibuyu\\Micro\\": "src/" "Meibuyu\\Micro\\": "src/"
}, },
"files": [ "files": [
"src/functions.php", "src/functions.php",
"src/const.php" "src/const.php"
] ]
}, },
"extra": { "extra": {
"hyperf": { "hyperf": {
"config": "Meibuyu\\Micro\\ConfigProvider" "config": "Meibuyu\\Micro\\ConfigProvider"
} }
} }
} }
File mode changed from 100644 to 100755
<?php <?php
/** /**
* 异步协程处理 * 异步协程处理
*/ */
namespace Meibuyu\Micro\Annotation; namespace Meibuyu\Micro\Annotation;
use Hyperf\Di\Annotation\AbstractAnnotation; use Hyperf\Di\Annotation\AbstractAnnotation;
/** /**
* @Annotation * @Annotation
* @Target("METHOD") * @Target("METHOD")
*/ */
class AsyncCoroutine extends AbstractAnnotation class AsyncCoroutine extends AbstractAnnotation
{ {
public function collectMethod(string $className, ?string $target): void public function collectMethod(string $className, ?string $target): void
{ {
parent::collectMethod($className, $target); // TODO: Change the autogenerated stub parent::collectMethod($className, $target); // TODO: Change the autogenerated stub
} }
} }
\ No newline at end of file
File mode changed from 100644 to 100755
<?php <?php
/** /**
* 日志追踪 写队列 批量更新到数据库 * 日志追踪 写队列 批量更新到数据库
*/ */
namespace Meibuyu\Micro\Annotation; namespace Meibuyu\Micro\Annotation;
use Hyperf\Di\Annotation\AbstractAnnotation; use Hyperf\Di\Annotation\AbstractAnnotation;
/** /**
* @Annotation * @Annotation
* @Target("METHOD") * @Target("METHOD")
*/ */
class LogTrace extends AbstractAnnotation class LogTrace extends AbstractAnnotation
{ {
public function collectMethod(string $className, ?string $target): void public function collectMethod(string $className, ?string $target): void
{ {
parent::collectMethod($className, $target); // TODO: Change the autogenerated stub parent::collectMethod($className, $target); // TODO: Change the autogenerated stub
} }
} }
\ No newline at end of file
File mode changed from 100644 to 100755
<?php <?php
namespace Meibuyu\Micro\Aspect; namespace Meibuyu\Micro\Aspect;
use Meibuyu\Micro\Handler\LogTrace\LogTraceHandler; use Meibuyu\Micro\Handler\LogTrace\LogTraceHandler;
use Hyperf\Di\Annotation\Aspect; use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect; use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint; use Hyperf\Di\Aop\ProceedingJoinPoint;
use Meibuyu\Micro\Annotation\AsyncCoroutine; use Meibuyu\Micro\Annotation\AsyncCoroutine;
use Hyperf\Utils\Coroutine; use Hyperf\Utils\Coroutine;
/** /**
* @Aspect( * @Aspect(
* annotations={ * annotations={
* AsyncCoroutine::class * AsyncCoroutine::class
* } * }
* ) * )
*/ */
class AsyncCoroutineAspect extends AbstractAspect class AsyncCoroutineAspect extends AbstractAspect
{ {
/** /**
* 优先级 * 优先级
* @var int * @var int
*/ */
public $priority = 998; public $priority = 998;
public function process(ProceedingJoinPoint $proceedingJoinPoint) public function process(ProceedingJoinPoint $proceedingJoinPoint)
{ {
// 切面切入后,执行对应的方法会由此来负责 // 切面切入后,执行对应的方法会由此来负责
// $proceedingJoinPoint 为连接点,通过该类的 process() 方法调用原方法并获得结果 // $proceedingJoinPoint 为连接点,通过该类的 process() 方法调用原方法并获得结果
// 在调用前进行某些处理 // 在调用前进行某些处理
return Coroutine::create(function ()use($proceedingJoinPoint){ return Coroutine::create(function ()use($proceedingJoinPoint){
LogTraceHandler::recordProcess( LogTraceHandler::recordProcess(
'投递到子协程任务,id:'.Coroutine::id() '投递到子协程任务,id:'.Coroutine::id()
.' ,类:'.$proceedingJoinPoint->className .' ,类:'.$proceedingJoinPoint->className
.' ,方法:'.$proceedingJoinPoint->methodName .' ,方法:'.$proceedingJoinPoint->methodName
.' ,参数:'.json_encode($proceedingJoinPoint->getArguments()) .' ,参数:'.json_encode($proceedingJoinPoint->getArguments())
, ,
true true
); );
$result = $proceedingJoinPoint->process(); $result = $proceedingJoinPoint->process();
LogTraceHandler::recordProcess( LogTraceHandler::recordProcess(
'子协程任务id:'.Coroutine::id().'已完成,执行结果:'. '子协程任务id:'.Coroutine::id().'已完成,执行结果:'.
json_encode($result),true json_encode($result),true
); );
}); });
} }
} }
\ No newline at end of file
<?php <?php
namespace Meibuyu\Micro\Aspect; namespace Meibuyu\Micro\Aspect;
use Hyperf\Di\Annotation\Aspect; use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect; use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint; use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Contract\RequestInterface;
use Meibuyu\Micro\Annotation\LogTrace; use Meibuyu\Micro\Annotation\LogTrace;
use Meibuyu\Micro\Handler\LogTrace\LogTraceHandler; use Meibuyu\Micro\Handler\LogTrace\LogTraceHandler;
/** /**
* @Aspect( * @Aspect(
* annotations={ * annotations={
* LogTrace::class * LogTrace::class
* } * }
* ) * )
*/ */
class LogTraceAspect extends AbstractAspect class LogTraceAspect extends AbstractAspect
{ {
/** /**
* 优先级 * 优先级
* @var int * @var int
*/ */
public $priority = 999; public $priority = 999;
public function process(ProceedingJoinPoint $proceedingJoinPoint) public function process(ProceedingJoinPoint $proceedingJoinPoint)
{ {
$originParams = [ $originParams = [
'called_params'=>$proceedingJoinPoint->getArguments(), 'called_params'=>$proceedingJoinPoint->getArguments(),
'http_params'=>make(RequestInterface::class)->all() 'http_params'=>make(RequestInterface::class)->all()
]; ];
LogTraceHandler::createLogTrace( LogTraceHandler::createLogTrace(
$proceedingJoinPoint->className.'@'.$proceedingJoinPoint->methodName, $proceedingJoinPoint->className.'@'.$proceedingJoinPoint->methodName,
$originParams $originParams
); );
$result = $proceedingJoinPoint->process(); $result = $proceedingJoinPoint->process();
LogTraceHandler::recordProcess('返回结果:'.json_encode($result)); LogTraceHandler::recordProcess('返回结果:'.json_encode($result));
return $result; return $result;
} }
} }
\ No newline at end of file
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
<?php <?php
/** /**
* 执行日志记录 * 执行日志记录
*/ */
namespace Meibuyu\Micro\Handler\LogTrace; namespace Meibuyu\Micro\Handler\LogTrace;
use Meibuyu\Micro\Model\LogTrace; use Meibuyu\Micro\Model\LogTrace;
use Hyperf\Utils\Coroutine; use Hyperf\Utils\Coroutine;
use Swoole\Server; use Swoole\Server;
use Throwable; use Throwable;
/** /**
* Class LogTraceHandler * Class LogTraceHandler
* @package App\Service * @package App\Service
*/ */
class LogTraceHandler class LogTraceHandler
{ {
/** /**
* 1.对执行操作进行的方法入口注解 LogTrace * 1.对执行操作进行的方法入口注解 LogTrace
2.对程序主动进行输出 2.对程序主动进行输出
try { try {
//流程1 //流程1
LogTraceHandler::recordProcess('执行到流程1'); LogTraceHandler::recordProcess('执行到流程1');
//流程2 //流程2
LogTraceHandler::recordProcess('执行到流程2'); LogTraceHandler::recordProcess('执行到流程2');
//记录输出数组 //记录输出数组
LogTraceHandler::recordProcess(['test'=>1]); LogTraceHandler::recordProcess(['test'=>1]);
//流程3 抛出一个异常 //流程3 抛出一个异常
throw new Exception('test111'); throw new Exception('test111');
//流程执行完成标记结束 //流程执行完成标记结束
LogTraceHandler::markComplete(); LogTraceHandler::markComplete();
}catch (\Throwable $exception){ }catch (\Throwable $exception){
//记录异常日志 //记录异常日志
LogTraceHandler::recordProcess($exception); LogTraceHandler::recordProcess($exception);
} }
* @param $params * @param $params
* @param $source * @param $source
* @return mixed * @return mixed
* @throws \Exception * @throws \Exception
*/ */
public static function createLogTrace($source, $params) public static function createLogTrace($source, $params)
{ {
if(!Coroutine::inCoroutine()) return; if(!Coroutine::inCoroutine()) return;
LogTrace::insertOrIgnore([ LogTrace::insertOrIgnore([
'request_id' => self::getRequestId(), 'request_id' => self::getRequestId(),
'origin_params' => json_encode($params), 'origin_params' => json_encode($params),
'source' => $source, 'source' => $source,
'created_at' => now(), 'created_at' => now(),
'process_info' => '' 'process_info' => ''
]); ]);
} }
/** /**
* @param bool $isInAsyncCoroutine * @param bool $isInAsyncCoroutine
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
private static function getRequestId($isInAsyncCoroutine=false) private static function getRequestId($isInAsyncCoroutine=false)
{ {
$workId = posix_getpid(); $workId = posix_getpid();
$cid = $isInAsyncCoroutine?Coroutine::parentId(Coroutine::id()):Coroutine::id(); $cid = $isInAsyncCoroutine?Coroutine::parentId(Coroutine::id()):Coroutine::id();
if(!$cid) throw new \Exception('无法使用协程标记录日志'); if(!$cid) throw new \Exception('无法使用协程标记录日志');
return container(Server::class)->stats()['start_time'] .$workId. $cid; return container(Server::class)->stats()['start_time'] .$workId. $cid;
} }
/** /**
* 程序执行完成标记结束 * 程序执行完成标记结束
* @throws \Exception * @throws \Exception
*/ */
public static function markComplete() public static function markComplete()
{ {
if(!Coroutine::inCoroutine()) return; if(!Coroutine::inCoroutine()) return;
container(LogTraceQueue::class)->addToQueue([ container(LogTraceQueue::class)->addToQueue([
'request_id'=>self::getRequestId(), 'request_id'=>self::getRequestId(),
'is_completed'=>YES 'is_completed'=>YES
]); ]);
//LogTrace::where('request_id', self::getRequestId())->update(['is_completed' => YES]); //LogTrace::where('request_id', self::getRequestId())->update(['is_completed' => YES]);
} }
/* /*
* 事务回滚导致部分流程日志无法记录 暂写到文件里 * 事务回滚导致部分流程日志无法记录 暂写到文件里
* 待写到Es后可以避免 * 待写到Es后可以避免
* 记录当前日志(包括异常捕获) * 记录当前日志(包括异常捕获)
*/ */
public static function recordProcess($track,$isInAsyncCoroutine=false) public static function recordProcess($track,$isInAsyncCoroutine=false)
{ {
if (empty($track)) return; if (empty($track)) return;
if(!Coroutine::inCoroutine()) return; if(!Coroutine::inCoroutine()) return;
$logInfo = ''; $logInfo = '';
if ($track instanceof Throwable) { if ($track instanceof Throwable) {
$logInfo = $track->getMessage() . "\n" . $logInfo = $track->getMessage() . "\n" .
$track->getFile() . " line:" . $track->getFile() . " line:" .
$track->getLine() . "\n" . $track->getLine() . "\n" .
$track->getTraceAsString(); $track->getTraceAsString();
} }
if (is_array($track)) { if (is_array($track)) {
$logInfo = var_export($track, true); $logInfo = var_export($track, true);
} }
if (is_string($track)||is_numeric($track)) { if (is_string($track)||is_numeric($track)) {
$logInfo = $track; $logInfo = $track;
} }
$logInfo .= "\n\n"; $logInfo .= "\n\n";
container(LogTraceQueue::class)->addToQueue([ container(LogTraceQueue::class)->addToQueue([
'request_id'=>self::getRequestId($isInAsyncCoroutine), 'request_id'=>self::getRequestId($isInAsyncCoroutine),
'process_info'=>$logInfo 'process_info'=>$logInfo
]); ]);
// $log = LogTrace::where('request_id', self::getRequestId())->first(); // $log = LogTrace::where('request_id', self::getRequestId())->first();
// if(empty($log)) return ; // if(empty($log)) return ;
// //
// $log->update([ // $log->update([
// 'process_info' => Db::raw("CONCAT(process_info,\"{$logInfo}\")") // 'process_info' => Db::raw("CONCAT(process_info,\"{$logInfo}\")")
// ]); // ]);
// //写入文件 // //写入文件
// put_log( // put_log(
// self::getRequestId()."\n". // self::getRequestId()."\n".
// $logInfo, // $logInfo,
// str_replace('\\','_',$log->source).'/'.today() // str_replace('\\','_',$log->source).'/'.today()
// ); // );
} }
// /** // /**
// * 记录流程日志 // * 记录流程日志
// * @param $funName // * @param $funName
// * @param $arguments // * @param $arguments
// * @throws \Exception // * @throws \Exception
// */ // */
// public static function __callStatic($funName, $arguments) // public static function __callStatic($funName, $arguments)
// { // {
// if(self::$instance){ // if(self::$instance){
// throw new \Exception('请用LogTraceService::createLogTrace 先实例化对象'); // throw new \Exception('请用LogTraceService::createLogTrace 先实例化对象');
// } // }
// self::$instance->$funName($arguments); // self::$instance->$funName($arguments);
// } // }
} }
\ No newline at end of file
<?php <?php
namespace Meibuyu\Micro\Handler\LogTrace; namespace Meibuyu\Micro\Handler\LogTrace;
use Meibuyu\Micro\Handler\RedisQueueBatchHandler; use Meibuyu\Micro\Handler\RedisQueueBatchHandler;
use Meibuyu\Micro\Model\LogTrace; use Meibuyu\Micro\Model\LogTrace;
class LogTraceQueue extends RedisQueueBatchHandler class LogTraceQueue extends RedisQueueBatchHandler
{ {
protected function specifyQueueName() protected function specifyQueueName()
{ {
$this->queue_name = env('APP_NAME').':LogTraceQueue'; $this->queue_name = env('APP_NAME').':LogTraceQueue';
} }
/** /**
* 具体批处理逻辑 * 具体批处理逻辑
* @param $dataArr * @param $dataArr
*/ */
function batchDeal($dataArr) function batchDeal($dataArr)
{ {
$updateArr = []; $updateArr = [];
$updateMarkComplete = []; $updateMarkComplete = [];
foreach ($dataArr as $arr){ foreach ($dataArr as $arr){
if(isset($arr['is_completed'])&&$arr['is_completed']==YES){ if(isset($arr['is_completed'])&&$arr['is_completed']==YES){
$updateMarkComplete[]= $arr['request_id'] ;continue; $updateMarkComplete[]= $arr['request_id'] ;continue;
} }
$updateArr[$arr['request_id']]['request_id'] = $arr['request_id']; $updateArr[$arr['request_id']]['request_id'] = $arr['request_id'];
$process_info = isset($updateArr[$arr['request_id']]['process_info'])? $process_info = isset($updateArr[$arr['request_id']]['process_info'])?
$updateArr[$arr['request_id']]['process_info']:''; $updateArr[$arr['request_id']]['process_info']:'';
$updateArr[$arr['request_id']]['process_info'] = $process_info.$arr['process_info']; $updateArr[$arr['request_id']]['process_info'] = $process_info.$arr['process_info'];
} }
//执行前先查一下 原先有的记录 避免被覆盖 //执行前先查一下 原先有的记录 避免被覆盖
$originLogs = LogTrace::whereIn('request_id',array_column($dataArr,'request_id')) $originLogs = LogTrace::whereIn('request_id',array_column($dataArr,'request_id'))
->pluck('process_info','request_id')->toArray(); ->pluck('process_info','request_id')->toArray();
//追加到原记录之后 //追加到原记录之后
$updateArr = array_map(function ($item)use($originLogs){ $updateArr = array_map(function ($item)use($originLogs){
if(!isset($originLogs[$item['request_id']])) return $item; if(!isset($originLogs[$item['request_id']])) return $item;
if(empty($originLogs[$item['request_id']])) return $item; if(empty($originLogs[$item['request_id']])) return $item;
$item['process_info'] = $originLogs[$item['request_id']].$item['process_info']; $item['process_info'] = $originLogs[$item['request_id']].$item['process_info'];
return $item; return $item;
},$updateArr); },$updateArr);
//批量更新 //批量更新
if(!empty($updateMarkComplete)){ if(!empty($updateMarkComplete)){
LogTrace::whereIn('request_id',$updateMarkComplete)->update(['is_completed'=>YES]); LogTrace::whereIn('request_id',$updateMarkComplete)->update(['is_completed'=>YES]);
} }
LogTrace::getModel()->batchUpdateByField(array_values($updateArr),'request_id'); LogTrace::getModel()->batchUpdateByField(array_values($updateArr),'request_id');
} }
} }
\ No newline at end of file
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
<?php <?php
namespace Meibuyu\Micro\Handler; namespace Meibuyu\Micro\Handler;
abstract class RedisQueueBatchHandler abstract class RedisQueueBatchHandler
{ {
/** /**
* 重试次数 * 重试次数
*/ */
protected $retrys=0; protected $retrys=0;
protected $queue_name; protected $queue_name;
const MAX_RETRY_TIMES = 3; const MAX_RETRY_TIMES = 3;
const BATCH_DEAL_NUM = 100; const BATCH_DEAL_NUM = 100;
const ERROR_RETRY_CODE = 9000; const ERROR_RETRY_CODE = 9000;
/** /**
* RedisQueueBatchHandler constructor. * RedisQueueBatchHandler constructor.
*/ */
public function __construct() public function __construct()
{ {
$this->specifyQueueName(); $this->specifyQueueName();
} }
/** /**
* 添加至队列 * 添加至队列
*/ */
public function addToQueue($data) public function addToQueue($data)
{ {
redis()->rPush($this->queue_name,json_encode($data)); redis()->rPush($this->queue_name,json_encode($data));
} }
/** /**
* 通过管道将执行失败的数据重回队列 * 通过管道将执行失败的数据重回队列
* @param $arr * @param $arr
* @param \Hyperf\Redis\Redis $redis * @param \Hyperf\Redis\Redis $redis
*/ */
protected function backToQueue($arr,\Hyperf\Redis\Redis $redis) protected function backToQueue($arr,\Hyperf\Redis\Redis $redis)
{ {
//开启管道 //开启管道
$pip = $redis->multi(); $pip = $redis->multi();
foreach ($arr as $i){ foreach ($arr as $i){
$pip->lPush($this->queue_name,$i); $pip->lPush($this->queue_name,$i);
} }
//批量提交 //批量提交
$pip->exec(); $pip->exec();
} }
//批处理具体逻辑 //批处理具体逻辑
abstract protected function batchDeal($data); abstract protected function batchDeal($data);
abstract protected function specifyQueueName(); abstract protected function specifyQueueName();
public function consume() public function consume()
{ {
$redis = redis(); $redis = redis();
while (true){ while (true){
//有数据则放回 否则延迟20s后返回空数组,同时可保持连接活跃 //有数据则放回 否则延迟20s后返回空数组,同时可保持连接活跃
//执行过程 如果redis服务异常,调用io操作时异常退出,框架重新拉起该进程 //执行过程 如果redis服务异常,调用io操作时异常退出,框架重新拉起该进程
$exist = $redis->blPop($this->queue_name,30); $exist = $redis->blPop($this->queue_name,30);
if(empty($exist)) continue ; if(empty($exist)) continue ;
$redis->lPush($this->queue_name,$exist[1]); $redis->lPush($this->queue_name,$exist[1]);
//每次从列表取100 //每次从列表取100
$arr = $redis->lRange($this->queue_name,0,self::BATCH_DEAL_NUM-1); $arr = $redis->lRange($this->queue_name,0,self::BATCH_DEAL_NUM-1);
//取完 从队列删掉 //取完 从队列删掉
$redis->lTrim($this->queue_name,count($arr),-1); $redis->lTrim($this->queue_name,count($arr),-1);
//数据格式化 //数据格式化
$formatArr = array_map(function ($item){ $formatArr = array_map(function ($item){
return json_decode($item,true); return json_decode($item,true);
},$arr); },$arr);
try { try {
//具体批处理逻辑 //具体批处理逻辑
$this->batchDeal($formatArr); $this->batchDeal($formatArr);
}catch (\Throwable $exception){ }catch (\Throwable $exception){
//错误码为100 通过管道从新推到队列 //错误码为100 通过管道从新推到队列
if($exception->getCode()==self::ERROR_RETRY_CODE){ if($exception->getCode()==self::ERROR_RETRY_CODE){
if($this->retrys<self::MAX_RETRY_TIMES){ //重试次数不超过3次 if($this->retrys<self::MAX_RETRY_TIMES){ //重试次数不超过3次
$this->backToQueue($arr,$redis); $this->backToQueue($arr,$redis);
$this->retrys++; $this->retrys++;
}else{ }else{
$this->retrys = 0; //重置当前次数 $this->retrys = 0; //重置当前次数
$this->errorWriteToFile($formatArr,$exception); $this->errorWriteToFile($formatArr,$exception);
} }
}else{ }else{
$this->errorWriteToFile($formatArr,$exception); $this->errorWriteToFile($formatArr,$exception);
} }
} }
} }
} }
/** /**
* @param $data * @param $data
* @param \Throwable $exception * @param \Throwable $exception
*/ */
private function errorWriteToFile($data, \Throwable $exception) private function errorWriteToFile($data, \Throwable $exception)
{ {
put_log( put_log(
json_encode($data)."\n". json_encode($data)."\n".
$exception->getMessage()."\n". $exception->getMessage()."\n".
$exception->getFile().' line:'. $exception->getFile().' line:'.
$exception->getLine()."\n". $exception->getLine()."\n".
$exception->getTraceAsString() $exception->getTraceAsString()
,'RedisQueue/'.$this->queue_name.'/'.today() ,'RedisQueue/'.$this->queue_name.'/'.today()
); );
} }
} }
\ No newline at end of file
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: Zero * User: Zero
* Date: 2020/3/30 * Date: 2020/3/30
* Time: 9:56 * Time: 9:56
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace Meibuyu\Micro\Manager; namespace Meibuyu\Micro\Manager;
use Hyperf\HttpMessage\Upload\UploadedFile; use Hyperf\HttpMessage\Upload\UploadedFile;
use Meibuyu\Micro\Exceptions\HttpResponseException; use Meibuyu\Micro\Exceptions\HttpResponseException;
class UploadManager class UploadManager
{ {
public static $pathPrefix = '/upload/'; public static $pathPrefix = '/upload/';
public static $options = [ public static $options = [
'path' => 'default', // 默认保存路径 'path' => 'default', // 默认保存路径
'maxSize' => 10 * 1024 * 1024, // 文件大小,10M 'maxSize' => 10 * 1024 * 1024, // 文件大小,10M
'temp' => false, // 是否为临时文件 'temp' => false, // 是否为临时文件
'mime' => ['jpeg', 'png', 'gif', 'jpg', 'svg', 'txt', 'pdf', 'xlsx', 'xls', 'doc', 'docx', 'rar', 'zip', 'csv'], // 允许上传的文件类型 'mime' => ['jpeg', 'png', 'gif', 'jpg', 'svg', 'txt', 'pdf', 'xlsx', 'xls', 'doc', 'docx', 'rar', 'zip', 'csv'], // 允许上传的文件类型
]; ];
/** /**
* 图片上传方法 * 图片上传方法
* @param $image * @param $image
* @param array $options * @param array $options
* @return string * @return string
* @throws HttpResponseException * @throws HttpResponseException
*/ */
public static function uploadImage($image, $options = []) public static function uploadImage($image, $options = [])
{ {
$imgOptions = [ $imgOptions = [
'path' => 'images', 'path' => 'images',
'mime' => ['jpeg', 'png', 'gif', 'jpg', 'svg'] 'mime' => ['jpeg', 'png', 'gif', 'jpg', 'svg']
]; ];
$options = array_merge($imgOptions, $options); $options = array_merge($imgOptions, $options);
return self::uploadFile($image, $options); return self::uploadFile($image, $options);
} }
/** /**
* 表格上传方法 * 表格上传方法
* @param $excel * @param $excel
* @param array $options * @param array $options
* @return string * @return string
* @throws HttpResponseException * @throws HttpResponseException
*/ */
public static function uploadExcel($excel, $options = []) public static function uploadExcel($excel, $options = [])
{ {
$excelOptions = [ $excelOptions = [
'path' => 'excel', 'path' => 'excel',
'mime' => ['xlsx', 'xls', 'csv'] 'mime' => ['xlsx', 'xls', 'csv']
]; ];
$options = array_merge($excelOptions, $options); $options = array_merge($excelOptions, $options);
return self::uploadFile($excel, $options); return self::uploadFile($excel, $options);
} }
/** /**
* 表格上传方法获取真实地址 * 表格上传方法获取真实地址
* @param $excel * @param $excel
* @param array $options * @param array $options
* @return string * @return string
* @throws HttpResponseException * @throws HttpResponseException
*/ */
public static function uploadExcelGetRealPath($excel, $options = []) public static function uploadExcelGetRealPath($excel, $options = [])
{ {
$excelOptions = [ $excelOptions = [
'path' => 'excel', 'path' => 'excel',
'mime' => ['xlsx', 'xls', 'csv'] 'mime' => ['xlsx', 'xls', 'csv']
]; ];
$options = array_merge($excelOptions, $options); $options = array_merge($excelOptions, $options);
return self::uploadFile($excel, $options, true); return self::uploadFile($excel, $options, true);
} }
/** /**
* 文件上传方法 * 文件上传方法
* @param UploadedFile $file 上传的文件 * @param UploadedFile $file 上传的文件
* @param array $options 配置参数 * @param array $options 配置参数
* @param bool $realPath * @param bool $realPath
* @return string * @return string
* @throws HttpResponseException * @throws HttpResponseException
*/ */
public static function uploadFile($file, $options = [], $realPath = false) public static function uploadFile($file, $options = [], $realPath = false)
{ {
$documentRoot = config('server.settings.document_root'); $documentRoot = config('server.settings.document_root');
if (!$documentRoot) { if (!$documentRoot) {
throw new \RuntimeException('未配置静态资源'); throw new \RuntimeException('未配置静态资源');
} }
$options = self::parseOptions($options); $options = self::parseOptions($options);
if ($file->isValid()) { if ($file->isValid()) {
$extension = strtolower($file->getExtension()); $extension = strtolower($file->getExtension());
// 通过扩展名判断类型 // 通过扩展名判断类型
if (!in_array($extension, $options['mime'])) { if (!in_array($extension, $options['mime'])) {
throw new HttpResponseException('文件类型不支持,目前只支持' . implode(',', $options['mime'])); throw new HttpResponseException('文件类型不支持,目前只支持' . implode(',', $options['mime']));
} }
// 判断文件大小 // 判断文件大小
if ($file->getSize() > $options['maxSize']) { if ($file->getSize() > $options['maxSize']) {
throw new HttpResponseException('文件超出系统规定的大小,最大不能超过' . num_2_file_size($options['maxSize'])); throw new HttpResponseException('文件超出系统规定的大小,最大不能超过' . num_2_file_size($options['maxSize']));
} }
// 文件重命名,由当前日期时间 + 唯一ID + 扩展名 // 文件重命名,由当前日期时间 + 唯一ID + 扩展名
$fileName = date('YmdHis') . uniqid() . '.' . $extension; $fileName = date('YmdHis') . uniqid() . '.' . $extension;
$savePath = self::parsePath($options, $documentRoot) . $fileName; $savePath = self::parsePath($options, $documentRoot) . $fileName;
$file->moveTo($savePath); $file->moveTo($savePath);
if ($file->isMoved()) { if ($file->isMoved()) {
if ($realPath) { if ($realPath) {
return $savePath; return $savePath;
} else { } else {
return str_replace($documentRoot, '', $savePath); return str_replace($documentRoot, '', $savePath);
} }
} else { } else {
throw new HttpResponseException('文件保存失败'); throw new HttpResponseException('文件保存失败');
} }
} else { } else {
throw new HttpResponseException('文件无效'); throw new HttpResponseException('文件无效');
} }
} }
/** /**
* 文件上传方法(micro-api-flow) * 文件上传方法(micro-api-flow)
* @param UploadedFile $file 上传的文件 * @param UploadedFile $file 上传的文件
* @param array $options 配置参数 * @param array $options 配置参数
* @param bool $realPath * @param bool $realPath
* @return string * @return string
* @throws HttpResponseException * @throws HttpResponseException
*/ */
public static function uploadFileGetName($file, $options = [], $realPath = false) public static function uploadFileGetName($file, $options = [], $realPath = false)
{ {
$documentRoot = config('server.settings.document_root'); $documentRoot = config('server.settings.document_root');
if (!$documentRoot) { if (!$documentRoot) {
throw new \RuntimeException('未配置静态资源'); throw new \RuntimeException('未配置静态资源');
} }
$options = self::parseOptions($options); $options = self::parseOptions($options);
if ($file->isValid()) { if ($file->isValid()) {
$extension = strtolower($file->getExtension()); $extension = strtolower($file->getExtension());
// 通过扩展名判断类型 // 通过扩展名判断类型
if (!in_array($extension, $options['mime'])) { if (!in_array($extension, $options['mime'])) {
throw new HttpResponseException('文件类型不支持,目前只支持' . implode(',', $options['mime'])); throw new HttpResponseException('文件类型不支持,目前只支持' . implode(',', $options['mime']));
} }
// 判断文件大小 // 判断文件大小
if ($file->getSize() > $options['maxSize']) { if ($file->getSize() > $options['maxSize']) {
throw new HttpResponseException('文件超出系统规定的大小,最大不能超过' . num_2_file_size($options['maxSize'])); throw new HttpResponseException('文件超出系统规定的大小,最大不能超过' . num_2_file_size($options['maxSize']));
} }
// 文件重命名,由当前日期时间 + 唯一ID + 扩展名 // 文件重命名,由当前日期时间 + 唯一ID + 扩展名
$fileName = date('YmdHis') . uniqid() . '.' . $extension; $fileName = date('YmdHis') . uniqid() . '.' . $extension;
$name = $file->toArray()['name']; $name = $file->toArray()['name'];
$savePath = self::parsePath($options, $documentRoot) . $fileName; $savePath = self::parsePath($options, $documentRoot) . $fileName;
$file->moveTo($savePath); $file->moveTo($savePath);
if ($file->isMoved()) { if ($file->isMoved()) {
if ($realPath) { if ($realPath) {
return $savePath . '?' . $name; return $savePath . '?' . $name;
} else { } else {
return str_replace($documentRoot, '', $savePath . '?' . $name); return str_replace($documentRoot, '', $savePath . '?' . $name);
} }
} else { } else {
throw new HttpResponseException('文件保存失败'); throw new HttpResponseException('文件保存失败');
} }
} else { } else {
throw new HttpResponseException('文件无效'); throw new HttpResponseException('文件无效');
} }
} }
/** /**
* 生成头像 * 生成头像
* @return string|string[] * @return string|string[]
*/ */
public static function createAvatar() public static function createAvatar()
{ {
$documentRoot = config('server.settings.document_root'); $documentRoot = config('server.settings.document_root');
if (!$documentRoot) { if (!$documentRoot) {
throw new \RuntimeException('未配置静态资源'); throw new \RuntimeException('未配置静态资源');
} }
$img = imagecreatetruecolor(180, 180); $img = imagecreatetruecolor(180, 180);
$bgColor = imagecolorallocate($img, 240, 240, 240); $bgColor = imagecolorallocate($img, 240, 240, 240);
imagefill($img, 0, 0, $bgColor); imagefill($img, 0, 0, $bgColor);
$color = imagecolorallocate($img, rand(90, 230), rand(90, 230), rand(90, 230)); $color = imagecolorallocate($img, rand(90, 230), rand(90, 230), rand(90, 230));
for ($i = 0; $i < 90; $i++) { for ($i = 0; $i < 90; $i++) {
for ($y = 0; $y < 180; $y++) { for ($y = 0; $y < 180; $y++) {
$ad = rand(10, 50); //随机 $ad = rand(10, 50); //随机
if ($ad % 3 == 0) { if ($ad % 3 == 0) {
for ($xx = $i; $xx < $i + 15; $xx++) { for ($xx = $i; $xx < $i + 15; $xx++) {
for ($yy = $y; $yy < $y + 30; $yy++) { for ($yy = $y; $yy < $y + 30; $yy++) {
imagesetpixel($img, $xx, $yy, $color); imagesetpixel($img, $xx, $yy, $color);
} }
} }
$is = ((90 - $i) + 90) - 15; //计算偏移 $is = ((90 - $i) + 90) - 15; //计算偏移
for ($xx = $is; $xx < $is + 15; $xx++) { for ($xx = $is; $xx < $is + 15; $xx++) {
for ($yy = $y; $yy < $y + 30; $yy++) { for ($yy = $y; $yy < $y + 30; $yy++) {
imagesetpixel($img, $xx, $yy, $color); imagesetpixel($img, $xx, $yy, $color);
} }
} }
} }
$y += 14; $y += 14;
} }
$i += 14; $i += 14;
} }
$path = $documentRoot . self::$pathPrefix . 'avatar/default/'; $path = $documentRoot . self::$pathPrefix . 'avatar/default/';
if (!is_dir($path)) { if (!is_dir($path)) {
mkdir($path, 0777, true); mkdir($path, 0777, true);
} }
$fileName = $path . date('YmdHis') . uniqid() . '.png'; $fileName = $path . date('YmdHis') . uniqid() . '.png';
imagepng($img, $fileName); imagepng($img, $fileName);
imagedestroy($img);//释放内存 imagedestroy($img);//释放内存
return str_replace($documentRoot, '', $fileName); return str_replace($documentRoot, '', $fileName);
} }
/** /**
* 处理保存路径 * 处理保存路径
* @param $options * @param $options
* @param $documentRoot * @param $documentRoot
* @return string * @return string
*/ */
public static function parsePath($options, $documentRoot) public static function parsePath($options, $documentRoot)
{ {
if (isset($options['temp']) && $options['temp']) { if (isset($options['temp']) && $options['temp']) {
// 如果是临时文件,修改保存路径为临时路径 // 如果是临时文件,修改保存路径为临时路径
$options['path'] = 'temp'; $options['path'] = 'temp';
} }
$path = $documentRoot . self::$pathPrefix . $options['path'] . '/' . date('Y-m-d'); $path = $documentRoot . self::$pathPrefix . $options['path'] . '/' . date('Y-m-d');
if (!is_dir($path)) { if (!is_dir($path)) {
// 判断路径是否存在,不存在,则创建 // 判断路径是否存在,不存在,则创建
mkdir($path, 0777, true); mkdir($path, 0777, true);
} }
return $path . '/'; return $path . '/';
} }
/** /**
* 处理配置参数 * 处理配置参数
* @param array $options * @param array $options
* @return array * @return array
*/ */
public static function parseOptions($options = []) public static function parseOptions($options = [])
{ {
if ($options == []) { if ($options == []) {
return self::$options; return self::$options;
} else { } else {
return array_merge(self::$options, $options); return array_merge(self::$options, $options);
} }
} }
public static function deleteFile($path) public static function deleteFile($path)
{ {
$documentRoot = config('server.settings.document_root'); $documentRoot = config('server.settings.document_root');
if (!$documentRoot) { if (!$documentRoot) {
throw new \RuntimeException('未配置静态资源'); throw new \RuntimeException('未配置静态资源');
} }
$path = str_replace(config('app_domain'), '', $path); $path = str_replace(config('app_domain'), '', $path);
$path = $documentRoot . $path; $path = $documentRoot . $path;
if (file_exists($path)) { if (file_exists($path)) {
unlink($path); unlink($path);
} }
} }
} }
<?php <?php
namespace Meibuyu\Micro\Middleware; namespace Meibuyu\Micro\Middleware;
use FastRoute\Dispatcher; use FastRoute\Dispatcher;
use Hyperf\HttpServer\Router\DispatcherFactory; use Hyperf\HttpServer\Router\DispatcherFactory;
use Hyperf\Utils\ApplicationContext; use Hyperf\Utils\ApplicationContext;
use Meibuyu\Micro\Model\Auth; use Meibuyu\Micro\Model\Auth;
use Meibuyu\Micro\Service\Interfaces\User\AuthenticationServiceInterface; use Meibuyu\Micro\Service\Interfaces\User\AuthenticationServiceInterface;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface; use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\Di\Annotation\Inject; use Hyperf\Di\Annotation\Inject;
class AuthorizeMiddleware implements MiddlewareInterface class AuthorizeMiddleware implements MiddlewareInterface
{ {
/** /**
* @Inject() * @Inject()
* @var AuthenticationServiceInterface * @var AuthenticationServiceInterface
*/ */
private $authorizationService; private $authorizationService;
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{ {
$path = $request->getUri()->getPath(); $path = $request->getUri()->getPath();
$token = token(); $token = token();
$applicationName = env('APP_NAME'); $applicationName = env('APP_NAME');
$method = $request->getMethod(); $method = $request->getMethod();
if (empty($path)) return $handler->handle($request); if (empty($path)) return $handler->handle($request);
//获取对应的 path 对应的权限,如果 path 是不需要登录鉴权,直接返回 //获取对应的 path 对应的权限,如果 path 是不需要登录鉴权,直接返回
$passed = $this->authRouter($applicationName, $path, $method, $token); $passed = $this->authRouter($applicationName, $path, $method, $token);
if ($passed) { if ($passed) {
return $handler->handle($request); return $handler->handle($request);
} }
return response()->withStatus(403)->json( return response()->withStatus(403)->json(
[ [
'code' => 403, 'code' => 403,
'msg' => "您没有访问接口的权限,请检查后再操作" 'msg' => "您没有访问接口的权限,请检查后再操作"
]); //鉴权失败,错误码 403 forbidden ]); //鉴权失败,错误码 403 forbidden
//path 是需要登录鉴权的,判断当前用户是佛有对应 path 的权限 //path 是需要登录鉴权的,判断当前用户是佛有对应 path 的权限
} }
/** /**
* 获取对应路由的权限,调用 RPC 服务 * 获取对应路由的权限,调用 RPC 服务
* @param $applicationName * @param $applicationName
* @param $route * @param $route
* @param $token * @param $token
* @return bool * @return bool
*/ */
protected function authRouter($applicationName, $path, $method, $token): bool protected function authRouter($applicationName, $path, $method, $token): bool
{ {
$userId = $this->getUserIdByToken($token); $userId = $this->getUserIdByToken($token);
$route = $this->getRouterByPath($path, $method); $route = $this->getRouterByPath($path, $method);
if (empty($route)) return true; //说明没有匹配到路由,直接 pass,后续执行一定会返回 404, 这里也可以直接 返回 404 if (empty($route)) return true; //说明没有匹配到路由,直接 pass,后续执行一定会返回 404, 这里也可以直接 返回 404
return $this->authorizationService->authByRouter($applicationName, $route, $method, $userId); return $this->authorizationService->authByRouter($applicationName, $route, $method, $userId);
} }
/** /**
* 根据 path 和 method 获取对应的 router * 根据 path 和 method 获取对应的 router
* @param string $path * @param string $path
* @param string $method * @param string $method
* @return array|string * @return array|string
*/ */
private function getRouterByPath(string $path, string $method) : string private function getRouterByPath(string $path, string $method) : string
{ {
$factory = ApplicationContext::getContainer()->get(DispatcherFactory::class); $factory = ApplicationContext::getContainer()->get(DispatcherFactory::class);
$dispatcher = $factory->getDispatcher('http'); $dispatcher = $factory->getDispatcher('http');
$routerMatched = $dispatcher->dispatch($method, $path); $routerMatched = $dispatcher->dispatch($method, $path);
$founded = $routerMatched[0]; $founded = $routerMatched[0];
if ( $founded != Dispatcher::FOUND) return ''; //说明没有匹配上路由,可以直接 return 404 not found if ( $founded != Dispatcher::FOUND) return ''; //说明没有匹配上路由,可以直接 return 404 not found
$handler = $routerMatched[1]; $handler = $routerMatched[1];
return $handler->route; return $handler->route;
} }
/** /**
* 根据 token 获取对应的 user_id * 根据 token 获取对应的 user_id
* @param $token * @param $token
* @return int|mixed * @return int|mixed
*/ */
protected function getUserIdByToken($token) protected function getUserIdByToken($token)
{ {
if (empty($token)) return 0; if (empty($token)) return 0;
$user = redis()->get($token); $user = redis()->get($token);
if ( ! $user) return 0; if ( ! $user) return 0;
$userArr = \json_decode($user, true); $userArr = \json_decode($user, true);
return !empty($userArr['id']) ? $userArr['id'] : 0; return !empty($userArr['id']) ? $userArr['id'] : 0;
} }
} }
\ No newline at end of file
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace Meibuyu\Micro\Model; namespace Meibuyu\Micro\Model;
use Hyperf\DbConnection\Model\Model ; use Hyperf\DbConnection\Model\Model ;
abstract class BaseModel extends Model abstract class BaseModel extends Model
{ {
/** /**
* Function addDataToMysql * Function addDataToMysql
* 批量插入数据到数据库,无则插入,重复则更新 * 批量插入数据到数据库,无则插入,重复则更新
*/ */
public function batchUpdateOrCreateByUniqueKey($data) public function batchUpdateOrCreateByUniqueKey($data)
{ {
$buildInsertBatchSqlStr = $this->buildInsertBatchSqlStr($data); $buildInsertBatchSqlStr = $this->buildInsertBatchSqlStr($data);
$sql = $buildInsertBatchSqlStr['sql']; $sql = $buildInsertBatchSqlStr['sql'];
return $this->getConnection()->update($sql); return $this->getConnection()->update($sql);
} }
/** /**
* Function buildInsertBatchSqlStr * Function buildInsertBatchSqlStr
* 组装mysql * 组装mysql
*/ */
private function buildInsertBatchSqlStr($data) private function buildInsertBatchSqlStr($data)
{ {
//从data中 获取更新的字段 //从data中 获取更新的字段
if (empty($data)) { if (empty($data)) {
return false; return false;
} }
$new_data=[]; $new_data=[];
$maxdim=$this->getmaxdim($data); $maxdim=$this->getmaxdim($data);
if($maxdim==1){ if($maxdim==1){
// 兼容一维数组 // 兼容一维数组
$new_data[]=$data; $new_data[]=$data;
}elseif($maxdim>2){ }elseif($maxdim>2){
// 大于2维返回false // 大于2维返回false
return false; return false;
}else{ }else{
$new_data=$data; $new_data=$data;
} }
$keys_arr = []; $keys_arr = [];
$datas_arr = []; $datas_arr = [];
$where_arr = []; $where_arr = [];
foreach ($new_data as $k => $v) { foreach ($new_data as $k => $v) {
if (!$keys_arr) { if (!$keys_arr) {
$keys_arr = array_keys($v); $keys_arr = array_keys($v);
} }
foreach ($v as $k2=>&$v2){ foreach ($v as $k2=>&$v2){
if(is_string($v2)){ if(is_string($v2)){
$v2="'".addslashes($v2)."'"; $v2="'".addslashes($v2)."'";
} }
} }
//数据重组 //数据重组
$onedata = "( " . implode(',', $v) . " )"; $onedata = "( " . implode(',', $v) . " )";
$datas_arr[] = $onedata; $datas_arr[] = $onedata;
unset($onedata); unset($onedata);
} }
// 组装格式 pt_uid=VALUES(pt_uid), // 组装格式 pt_uid=VALUES(pt_uid),
foreach ($keys_arr as $k2 => $v2) { foreach ($keys_arr as $k2 => $v2) {
$where_arr[] = "$v2 = VALUES($v2)"; $where_arr[] = "$v2 = VALUES($v2)";
} }
$keys_str = implode(',', $keys_arr); $keys_str = implode(',', $keys_arr);
$datas_str = implode(',', $datas_arr); $datas_str = implode(',', $datas_arr);
$where_str = implode(',', $where_arr); $where_str = implode(',', $where_arr);
$sql = ""; $sql = "";
if ($keys_str && $datas_str && $where_str) { if ($keys_str && $datas_str && $where_str) {
$table = $this->getTable(); $table = $this->getTable();
$sql = " INSERT INTO $table ( $keys_str ) VALUES $datas_str ON DUPLICATE KEY UPDATE $where_str"; $sql = " INSERT INTO $table ( $keys_str ) VALUES $datas_str ON DUPLICATE KEY UPDATE $where_str";
} }
unset($keys_str, $where_str); unset($keys_str, $where_str);
return ['sql' => $sql, 'count' => count($datas_arr)]; return ['sql' => $sql, 'count' => count($datas_arr)];
} }
/** /**
* Function getmaxdim * Function getmaxdim
* 数组维数 * 数组维数
*/ */
private function getmaxdim($vDim){ private function getmaxdim($vDim){
if(!is_array($vDim)) return 0; if(!is_array($vDim)) return 0;
else { else {
$max1 = 0; $max1 = 0;
foreach($vDim as $item1) { foreach($vDim as $item1) {
$t1 = $this->getmaxdim($item1); $t1 = $this->getmaxdim($item1);
if( $t1 > $max1) $max1 = $t1; if( $t1 > $max1) $max1 = $t1;
} }
return $max1 + 1; return $max1 + 1;
} }
} }
/** /**
* 批量更新数组 有则 * 批量更新数组 有则
* @param $data array 待更新的数据,二维数组格式 * @param $data array 待更新的数据,二维数组格式
* @param string $field string 值不同的条件,默认为id * @param string $field string 值不同的条件,默认为id
* @return bool|string * @return bool|string
*/ */
public function batchUpdateByField($data, $field = null) public function batchUpdateByField($data, $field = null)
{ {
if(is_null($field)) $field = $this->getKeyName(); if(is_null($field)) $field = $this->getKeyName();
if (!is_array($data) || !$field ) { if (!is_array($data) || !$field ) {
return false; return false;
} }
$updates = $this->parseUpdate($data, $field); $updates = $this->parseUpdate($data, $field);
// 获取所有键名为$field列的值,值两边加上单引号,保存在$fields数组中 // 获取所有键名为$field列的值,值两边加上单引号,保存在$fields数组中
// array_column()函数需要PHP5.5.0+,如果小于这个版本,可以自己实现, // array_column()函数需要PHP5.5.0+,如果小于这个版本,可以自己实现,
// 参考地址:http://php.net/manual/zh/function.array-column.php#118831 // 参考地址:http://php.net/manual/zh/function.array-column.php#118831
$fields = array_column($data, $field); $fields = array_column($data, $field);
$fields = implode(',', array_map(function($value) { $fields = implode(',', array_map(function($value) {
return "'".$value."'"; return "'".$value."'";
}, $fields)); }, $fields));
$sql = sprintf( $sql = sprintf(
"UPDATE `%s` SET %s WHERE `%s` IN (%s) ", "UPDATE `%s` SET %s WHERE `%s` IN (%s) ",
$this->getTable(), $updates, $field, $fields $this->getTable(), $updates, $field, $fields
); );
return $this->getConnection()->update($sql); return $this->getConnection()->update($sql);
} }
/** /**
* 将二维数组转换成CASE WHEN THEN的批量更新条件 * 将二维数组转换成CASE WHEN THEN的批量更新条件
* @param $data array 二维数组 * @param $data array 二维数组
* @param $field string 列名 * @param $field string 列名
* @return string sql语句 * @return string sql语句
*/ */
private function parseUpdate($data, $field) private function parseUpdate($data, $field)
{ {
$sql = ''; $sql = '';
$keys = array_keys(current($data)); $keys = array_keys(current($data));
foreach ($keys as $column) { foreach ($keys as $column) {
if($column==$keys) continue; if($column==$keys) continue;
$sql .= sprintf("`%s` = CASE `%s` \n", $column, $field); $sql .= sprintf("`%s` = CASE `%s` \n", $column, $field);
foreach ($data as $line) { foreach ($data as $line) {
$sql .= sprintf( $sql .= sprintf(
"WHEN '%s' THEN '%s' \n", "WHEN '%s' THEN '%s' \n",
$line[$field], $line[$field],
!is_numeric($line[$column])?addslashes($line[$column]):$line[$column] !is_numeric($line[$column])?addslashes($line[$column]):$line[$column]
); );
} }
$sql .= "END,"; $sql .= "END,";
} }
return rtrim($sql, ','); return rtrim($sql, ',');
} }
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: Auto generated. * User: Auto generated.
* Date: 2022-01-20 * Date: 2022-01-20
* Time: 10:08:03 * Time: 10:08:03
* Description: * Description:
*/ */
declare (strict_types=1); declare (strict_types=1);
namespace Meibuyu\Micro\Model; namespace Meibuyu\Micro\Model;
/** /**
* 模型类 LogTrace * 模型类 LogTrace
* @package App\Model * @package App\Model
* @property integer $id * @property integer $id
* @property string $source 路径 * @property string $source 路径
* @property string $origin_params * @property string $origin_params
* @property integer $is_completed * @property integer $is_completed
* @property string $created_at * @property string $created_at
* @property string $process_info * @property string $process_info
*/ */
class LogTrace extends BaseModel class LogTrace extends BaseModel
{ {
protected $table = 'trace_logs'; protected $table = 'trace_logs';
/** /**
* 是否使用时间戳管理 * 是否使用时间戳管理
* @var bool * @var bool
*/ */
public $timestamps = false; public $timestamps = false;
/** /**
* 可写入数据的字段. * 可写入数据的字段.
* @var array * @var array
*/ */
protected $fillable = [ protected $fillable = [
'source', 'source',
'origin_params', 'origin_params',
'is_completed', 'is_completed',
'process_info', 'process_info',
]; ];
} }
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 王源 * User: 王源
* Date: 2020/1/9 * Date: 2020/1/9
* Time: 15:08 * Time: 15:08
*/ */
namespace Meibuyu\Micro\Service; namespace Meibuyu\Micro\Service;
use Exception; use Exception;
use Hyperf\DbConnection\Model\Model; use Hyperf\DbConnection\Model\Model;
use Meibuyu\Micro\Helper; use Meibuyu\Micro\Helper;
/** /**
* @deprecated 此类废弃,在之后的版本会被删除 * @deprecated 此类废弃,在之后的版本会被删除
*/ */
class BaseService class BaseService
{ {
/** /**
* @var Model * @var Model
*/ */
protected $model; protected $model;
/** /**
* 查找一个数据 * 查找一个数据
* @param $id * @param $id
* @return Model | array * @return Model | array
*/ */
protected function find($id) protected function find($id)
{ {
$model = $this->model->find($id); $model = $this->model->find($id);
return $model; return $model;
} }
public function all(array $columns = ['*'], array $relations = []): array public function all(array $columns = ['*'], array $relations = []): array
{ {
return $this->model->with($relations)->get($columns)->toArray(); return $this->model->with($relations)->get($columns)->toArray();
} }
/** /**
* 获取一条数据 * 获取一条数据
* @param int $id * @param int $id
* @param array $columns * @param array $columns
* @param array $relations * @param array $relations
* @return mixed * @return mixed
*/ */
public function get(int $id, array $columns = ['*'], array $relations = []) public function get(int $id, array $columns = ['*'], array $relations = [])
{ {
return $this->model->with($relations)->find($id, $columns); return $this->model->with($relations)->find($id, $columns);
} }
/** /**
* 插入一条数据 * 插入一条数据
* @param array $params * @param array $params
* @return array * @return array
*/ */
public function insert($params) public function insert($params)
{ {
try { try {
$res = $this->model->insert($params); $res = $this->model->insert($params);
return Helper::success($res); return Helper::success($res);
} catch (Exception $e) { } catch (Exception $e) {
return Helper::fail('', $e->getMessage()); return Helper::fail('', $e->getMessage());
} }
} }
/** /**
* 新增一条数据 * 新增一条数据
* @param array $params * @param array $params
* @return array * @return array
*/ */
public function create($params) public function create($params)
{ {
try { try {
$model = $this->model->newInstance($params); $model = $this->model->newInstance($params);
$model->save(); $model->save();
return Helper::success($model); return Helper::success($model);
} catch (Exception $e) { } catch (Exception $e) {
return Helper::fail('', $e->getMessage()); return Helper::fail('', $e->getMessage());
} }
} }
/** /**
* 更新数据 * 更新数据
* @param $id * @param $id
* @param array $params * @param array $params
* @return array * @return array
*/ */
public function update($id, $params) public function update($id, $params)
{ {
try { try {
$model = $this->find($id); $model = $this->find($id);
$model->fill($params); $model->fill($params);
$model->save(); $model->save();
return Helper::success($model); return Helper::success($model);
} catch (Exception $e) { } catch (Exception $e) {
return Helper::fail('', $e->getMessage()); return Helper::fail('', $e->getMessage());
} }
} }
/** /**
* 删除数据 * 删除数据
* @param $id * @param $id
* @return array * @return array
*/ */
public function delete($id) public function delete($id)
{ {
try { try {
$model = $this->find($id); $model = $this->find($id);
$res = $model->delete(); $res = $model->delete();
if ($res) { if ($res) {
return Helper::success($res, '删除成功'); return Helper::success($res, '删除成功');
} else { } else {
return Helper::fail($res, '删除失败'); return Helper::fail($res, '删除失败');
} }
} catch (Exception $e) { } catch (Exception $e) {
return Helper::fail('', $e->getMessage()); return Helper::fail('', $e->getMessage());
} }
} }
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: zero * User: zero
* Date: 2020/3/27 * Date: 2020/3/27
* Time: 15:03 * Time: 15:03
*/ */
namespace Meibuyu\Micro\Service\Interfaces; namespace Meibuyu\Micro\Service\Interfaces;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\App\AppServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\App\AppServiceInterface
*/ */
interface AppServiceInterface interface AppServiceInterface
{ {
/** /**
* 获取当前用户可访问的应用数组 * 获取当前用户可访问的应用数组
* @param $user * @param $user
* @param bool $isSuperAdmin 是否是超级管理员 * @param bool $isSuperAdmin 是否是超级管理员
* @return mixed * @return mixed
*/ */
public function getAccessApps($user, $isSuperAdmin = false); public function getAccessApps($user, $isSuperAdmin = false);
/** /**
* 获取单个数据 * 获取单个数据
* @param int $id * @param int $id
* @param array $relations 关联关系只有['group'] * @param array $relations 关联关系只有['group']
* @param array $columns * @param array $columns
* @return mixed * @return mixed
*/ */
public function get(int $id, array $relations = [], array $columns = ['id', 'title']); public function get(int $id, array $relations = [], array $columns = ['id', 'title']);
/** /**
* 通过id列表获取应用数组 * 通过id列表获取应用数组
* @param array $idList 默认去重 * @param array $idList 默认去重
* @param array $relations 关联关系只有['group'] * @param array $relations 关联关系只有['group']
* @param array $columns 默认展示id和title,可传['title', 'name', 'entry', 'prefix', 'group_id', 'is_inside', 'is_active', 'icon', 'desc', 'weight'] * @param array $columns 默认展示id和title,可传['title', 'name', 'entry', 'prefix', 'group_id', 'is_inside', 'is_active', 'icon', 'desc', 'weight']
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
*/ */
public function getByIdList(array $idList, array $relations = [], array $columns = ['id', 'title']): array; public function getByIdList(array $idList, array $relations = [], array $columns = ['id', 'title']): array;
/** /**
* 通过name列表获取应用数组 * 通过name列表获取应用数组
* @param array $nameList 默认去重 * @param array $nameList 默认去重
* @param array $relations 关联关系只有['group'] * @param array $relations 关联关系只有['group']
* @param array $columns 默认展示id和title,可传['title', 'name', 'entry', 'prefix', 'group_id', 'is_inside', 'is_active', 'icon', 'desc', 'weight'] * @param array $columns 默认展示id和title,可传['title', 'name', 'entry', 'prefix', 'group_id', 'is_inside', 'is_active', 'icon', 'desc', 'weight']
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
*/ */
public function getByNameList(array $nameList, array $relations = [], array $columns = ['id', 'title', 'name']): array; public function getByNameList(array $nameList, array $relations = [], array $columns = ['id', 'title', 'name']): array;
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 王源 * User: 王源
* Date: 2020/1/9 * Date: 2020/1/9
* Time: 15:07 * Time: 15:07
*/ */
namespace Meibuyu\Micro\Service\Interfaces; namespace Meibuyu\Micro\Service\Interfaces;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\User\BaseInfoServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\User\BaseInfoServiceInterface
*/ */
interface BaseInfoServiceInterface interface BaseInfoServiceInterface
{ {
/** /**
* 通过单个id获取岗位数组 * 通过单个id获取岗位数组
* @param int $id * @param int $id
* @param array $columns * @param array $columns
* @param array $relations * @param array $relations
* @return array * @return array
*/ */
public function getPositionListById(int $id): array; public function getPositionListById(int $id): array;
/** /**
* 通过单个id获取岗位向上取数组 * 通过单个id获取岗位向上取数组
* @param int $id * @param int $id
* @param null $level * @param null $level
* @return array * @return array
*/ */
public function getPositionWithTopListById(int $id, $level = null): array; public function getPositionWithTopListById(int $id, $level = null): array;
/** /**
* 通过id数组获取国家数组 * 通过id数组获取国家数组
* @param array $idList 默认去重 * @param array $idList 默认去重
* @param array $columns * @param array $columns
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getCountryListByIdList(array $idList, array $columns = ['*']): array; public function getCountryListByIdList(array $idList, array $columns = ['*']): array;
/** /**
* 通过id数组获取国家区域数组 * 通过id数组获取国家区域数组
* @param array $ids 默认去重 * @param array $ids 默认去重
* @param array $relations ['country'] 可关联国家数据 * @param array $relations ['country'] 可关联国家数据
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getCountryAreaListByIdList(array $ids, array $relations = []): array; public function getCountryAreaListByIdList(array $ids, array $relations = []): array;
/** /**
* 通过id数组获取团队数组 * 通过id数组获取团队数组
* @param array $idList 默认去重 * @param array $idList 默认去重
* @param array $columns * @param array $columns
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getTeamListByIdList(array $idList, array $columns = ['id', 'name']): array; public function getTeamListByIdList(array $idList, array $columns = ['id', 'name']): array;
/** /**
* 通过id数组获取站点数组 * 通过id数组获取站点数组
* @param array $idList 默认去重 * @param array $idList 默认去重
* @param array $columns * @param array $columns
* @param array $relations $relations 支持的关联关系 ['team', 'country'] 分别代表 团队、国家、 * @param array $relations $relations 支持的关联关系 ['team', 'country'] 分别代表 团队、国家、
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getSiteListByIdList(array $idList, array $columns = ['id', 'name'], array $relations = []): array; public function getSiteListByIdList(array $idList, array $columns = ['id', 'name'], array $relations = []): array;
/** /**
* 通过id数组获取货币数组 * 通过id数组获取货币数组
* @param array $idList 默认去重 * @param array $idList 默认去重
* @param array $columns * @param array $columns
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getCurrencyListByIdList(array $idList, array $columns = ['id', 'name']): array; public function getCurrencyListByIdList(array $idList, array $columns = ['id', 'name']): array;
/** /**
* 通过Keyword获取货币id数组 * 通过Keyword获取货币id数组
* @param $keyword * @param $keyword
* @return array * @return array
*/ */
public function getCurrencyIdsByKeyword($keyword); public function getCurrencyIdsByKeyword($keyword);
/** /**
* 通过单个id获取岗位信息 * 通过单个id获取岗位信息
* @param int $id 职位id * @param int $id 职位id
* @param array $relations 职位的关联信息 支持["position_level","users","parent" * @param array $relations 职位的关联信息 支持["position_level","users","parent"
* ,"children","perms"] 分别是 岗位职级,岗位用户,岗位父级,岗位子集,岗位对应的权限 * ,"children","perms"] 分别是 岗位职级,岗位用户,岗位父级,岗位子集,岗位对应的权限
* @param array $columns 默认显示所有字段 * @param array $columns 默认显示所有字段
* @return array|null * @return array|null
*/ */
public function getPositionById(int $id, array $relations = [], array $columns = ['*']); public function getPositionById(int $id, array $relations = [], array $columns = ['*']);
/** /**
* 根据id获取单个数据 * 根据id获取单个数据
* @param int $id 货币id * @param int $id 货币id
* @param array $columns 要显示的字段 默认全部 ['id', 'name', 'code', 'symbol'] * @param array $columns 要显示的字段 默认全部 ['id', 'name', 'code', 'symbol']
* @return array|null * @return array|null
*/ */
public function getCurrencyById($id, array $columns = ['id', 'name', 'code', 'symbol']); public function getCurrencyById($id, array $columns = ['id', 'name', 'code', 'symbol']);
/** /**
* 根据id获取单个数据 * 根据id获取单个数据
* @param int $id * @param int $id
* @param array $columns 要显示的字段 默认全部 * @param array $columns 要显示的字段 默认全部
* @return array|null * @return array|null
*/ */
public function getCountryById($id, array $columns = ['*']); public function getCountryById($id, array $columns = ['*']);
/** /**
* 获取单个团队数据 * 获取单个团队数据
* @param int $id * @param int $id
* @param array $relations 支持的关联关系 ['leader', 'sites', "users", "parent", "children"] 分别代表 负责人、团队下的站点、团队成员、父级团队,再级团队 * @param array $relations 支持的关联关系 ['leader', 'sites', "users", "parent", "children"] 分别代表 负责人、团队下的站点、团队成员、父级团队,再级团队
* @param array $columns 要显示的字段 默认['id', 'pid', "name", "leader_user_id", "department_id"] * @param array $columns 要显示的字段 默认['id', 'pid', "name", "leader_user_id", "department_id"]
* @return array|null * @return array|null
*/ */
public function getTeamById($id, array $relations = [], array $columns = ['id', 'pid', "name", "leader_user_id", "department_id"]); public function getTeamById($id, array $relations = [], array $columns = ['id', 'pid', "name", "leader_user_id", "department_id"]);
/** /**
* 获取单个站点数据 * 获取单个站点数据
* @param int $id * @param int $id
* @param array $relations $relations 支持的关联关系 ['team', 'country'] 分别代表 团队、国家、 * @param array $relations $relations 支持的关联关系 ['team', 'country'] 分别代表 团队、国家、
* @param array $columns 要显示的字段 默认['id', "name", "url", "country_id", "team_id"] * @param array $columns 要显示的字段 默认['id', "name", "url", "country_id", "team_id"]
* @return array|null * @return array|null
*/ */
public function getSiteById($id, array $relations = [], array $columns = ['id', "name", "url", "country_id", "team_id"]); public function getSiteById($id, array $relations = [], array $columns = ['id', "name", "url", "country_id", "team_id"]);
/** /**
* 根据团队id获取对应的站点列表 * 根据团队id获取对应的站点列表
* @param int $teamId 团队id * @param int $teamId 团队id
* @param array $relations $relations 支持的关联关系 ['team', 'country'] 分别代表 团队、国家、 * @param array $relations $relations 支持的关联关系 ['team', 'country'] 分别代表 团队、国家、
* @param array $columns 要显示的字段 默认['id', "name", "url", "country_id", "team_id"] * @param array $columns 要显示的字段 默认['id', "name", "url", "country_id", "team_id"]
* @return array|null * @return array|null
*/ */
public function getSiteListByTeamId($teamId, array $relations = [], array $columns = ['id', "name", "url", "country_id", "team_id"]); public function getSiteListByTeamId($teamId, array $relations = [], array $columns = ['id', "name", "url", "country_id", "team_id"]);
/** /**
* 返回所有货币数据 * 返回所有货币数据
* @param array $columns 要显示的字段 * @param array $columns 要显示的字段
* $columns = ['id', 'name', 'code', 'symbol']; * $columns = ['id', 'name', 'code', 'symbol'];
* @return array 默认已keyBy('id') * @return array 默认已keyBy('id')
*/ */
public function currencies(array $columns = ['id', 'name']): array; public function currencies(array $columns = ['id', 'name']): array;
/** /**
* 获取所有国家数据 * 获取所有国家数据
* @param array $columns 要显示的字段 * @param array $columns 要显示的字段
* $columns = ['id', 'name', 'iso_code2', 'iso_code3']; * $columns = ['id', 'name', 'iso_code2', 'iso_code3'];
* @return array 默认已keyBy('id') * @return array 默认已keyBy('id')
*/ */
public function countries(array $columns = ['id', 'name']): array; public function countries(array $columns = ['id', 'name']): array;
/** /**
* 获取所有团队数据 * 获取所有团队数据
* @param array $relations 支持的关联关系 ['leader', 'sites', "users", "parent", "children"] 分别代表 负责人、团队下的站点、团队成员、父级团队,再级团队 * @param array $relations 支持的关联关系 ['leader', 'sites', "users", "parent", "children"] 分别代表 负责人、团队下的站点、团队成员、父级团队,再级团队
* @param array $columns 要显示的字段 * @param array $columns 要显示的字段
* $columns = ['id', 'pid', "name", "leader_user_id", "leader_user_id", "department_id"]; * $columns = ['id', 'pid', "name", "leader_user_id", "leader_user_id", "department_id"];
* @return array 默认已keyBy('id') * @return array 默认已keyBy('id')
*/ */
public function teams(array $relations = [], array $columns = ['id', 'pid', "name", "leader_user_id", "department_id"]): array; public function teams(array $relations = [], array $columns = ['id', 'pid', "name", "leader_user_id", "department_id"]): array;
/** /**
* 获取所有站点的数据 * 获取所有站点的数据
* @param array $relations 支持的关联关系 ['team', 'country'] 分别代表 团队、国家 * @param array $relations 支持的关联关系 ['team', 'country'] 分别代表 团队、国家
* @param array $columns 要显示的字段 * @param array $columns 要显示的字段
* $columns = ['id', "name", "url", "country_id", "team_id"]; * $columns = ['id', "name", "url", "country_id", "team_id"];
* @return array 默认已keyBy('id') * @return array 默认已keyBy('id')
*/ */
public function sites(array $relations = [], array $columns = ['id', "name"]): array; public function sites(array $relations = [], array $columns = ['id', "name"]): array;
/** /**
* 获取部门领导id数据 * 获取部门领导id数据
* @param array $ids 部门id数组 * @param array $ids 部门id数组
* @return array * @return array
*/ */
public function getDepartmentLeaderIdsByIds($ids); public function getDepartmentLeaderIdsByIds($ids);
/** /**
* 获取审阅人员 * 获取审阅人员
* @param $teamId * @param $teamId
* @param $authId * @param $authId
* @return array|bool * @return array|bool
*/ */
public function getReviewUsers($teamId, $authId); public function getReviewUsers($teamId, $authId);
/** /**
* 通过id数组获取部门数组 * 通过id数组获取部门数组
* @param array $idList 默认去重 * @param array $idList 默认去重
* @param array $relations 关联关系,默认空 ['users', 'leader'] * @param array $relations 关联关系,默认空 ['users', 'leader']
* @param array $columns 要显示的字段,默认全部 ['id', 'name', 'pid', 'remark'] * @param array $columns 要显示的字段,默认全部 ['id', 'name', 'pid', 'remark']
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getDepartmentListByIdList(array $idList, array $relations = [], array $columns = ['*']): array; public function getDepartmentListByIdList(array $idList, array $relations = [], array $columns = ['*']): array;
/** /**
* 获取单个部门数据 * 获取单个部门数据
* @param int $id * @param int $id
* @param array $relations 关联关系,默认空 ['users', 'leader'] * @param array $relations 关联关系,默认空 ['users', 'leader']
* @param array $columns 要显示的字段,默认全部 ['id', 'name', 'pid', 'remark'] * @param array $columns 要显示的字段,默认全部 ['id', 'name', 'pid', 'remark']
* @return array|null * @return array|null
*/ */
public function getDepartmentById($id, array $relations = [], array $columns = ['*']); public function getDepartmentById($id, array $relations = [], array $columns = ['*']);
/** /**
* 获取所有部门数据 * 获取所有部门数据
* @param array $relations 关联关系,默认空 ['users', 'leader'] * @param array $relations 关联关系,默认空 ['users', 'leader']
* @param array $columns 要显示的字段,默认全部 ['id', 'name', 'pid', 'remark'] * @param array $columns 要显示的字段,默认全部 ['id', 'name', 'pid', 'remark']
* @return array 默认已keyBy('id') * @return array 默认已keyBy('id')
*/ */
public function departments(array $relations = [], array $columns = ['*']): array; public function departments(array $relations = [], array $columns = ['*']): array;
/** /**
* 通过职级id数组获取用户占比数组 * 通过职级id数组获取用户占比数组
* @param array $positionLevelIds 职级id数组,默认去重 * @param array $positionLevelIds 职级id数组,默认去重
* @return array * @return array
* @author Zero * @author Zero
*/ */
public function getRateByPositionLevelIds(array $positionLevelIds): array; public function getRateByPositionLevelIds(array $positionLevelIds): array;
/** /**
* 通过单个id获取国家地区信息 * 通过单个id获取国家地区信息
* @param int $id 职位id * @param int $id 职位id
* @param array $columns 默认显示所有字段 * @param array $columns 默认显示所有字段
* @return array|null * @return array|null
*/ */
public function getCountryZoneById(int $id, array $columns = ['*']); public function getCountryZoneById(int $id, array $columns = ['*']);
/** /**
* 根据国家code数组获取国家数组 * 根据国家code数组获取国家数组
* @param array $codes 国家code数组 * @param array $codes 国家code数组
* @param array $columns 获取的字段,默认全部 * @param array $columns 获取的字段,默认全部
* @param int $codeType 2/3 (iso_code2/iso_code3) * @param int $codeType 2/3 (iso_code2/iso_code3)
* @return array 默认已keyBy('iso_code') * @return array 默认已keyBy('iso_code')
* @author Zero * @author Zero
*/ */
public function getCountriesByCodes(array $codes, array $columns = ['*'], $codeType = 2); public function getCountriesByCodes(array $codes, array $columns = ['*'], $codeType = 2);
/** /**
* 根据国家地区code数组获取国家地区数组 * 根据国家地区code数组获取国家地区数组
* @param array $codes 国家code数组 * @param array $codes 国家code数组
* @param null $countryId 国家id * @param null $countryId 国家id
* @param array $relations 关联关系,默认空 可填['country'] * @param array $relations 关联关系,默认空 可填['country']
* @return array * @return array
* @author Zero * @author Zero
*/ */
public function getCountryZonesByCodes(array $codes, $countryId = null, array $relations = []); public function getCountryZonesByCodes(array $codes, $countryId = null, array $relations = []);
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 王源 * User: 王源
* Date: 2020/3/16 * Date: 2020/3/16
* Time: 15:07 * Time: 15:07
*/ */
namespace Meibuyu\Micro\Service\Interfaces; namespace Meibuyu\Micro\Service\Interfaces;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Datacenter\DatacenterServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Datacenter\DatacenterServiceInterface
*/ */
interface DatacenterServiceInterface interface DatacenterServiceInterface
{ {
/** /**
* description:获取国家汇率 默认取最新一个汇率值 * description:获取国家汇率 默认取最新一个汇率值
* author: fuyunnan * author: fuyunnan
* @param int $currencyId 货币id * @param int $currencyId 货币id
* @param array $field 字段 * @param array $field 字段
* @param array $where 筛选数组 * @param array $where 筛选数组
* @return array * @return array
* @throws * @throws
* Date: 2020/8/11 * Date: 2020/8/11
*/ */
public function getCurrencyRate($currencyId, $field = ['id', 'currency_id', 'rate_val'], $where = []): array; public function getCurrencyRate($currencyId, $field = ['id', 'currency_id', 'rate_val'], $where = []): array;
/** /**
* description:获取国家汇率 默认取最新一个汇率值 * description:获取国家汇率 默认取最新一个汇率值
* author: fuyunnan * author: fuyunnan
* @param array $currencyIds 货币ids * @param array $currencyIds 货币ids
* @param array $field 字段 * @param array $field 字段
* @param array $where 筛选数组 * @param array $where 筛选数组
* @return array * @return array
* @throws * @throws
* Date: 2020/8/11 * Date: 2020/8/11
*/ */
public function getCurrencyListRate($currencyIds, $field = ['id', 'currency_id', 'rate_val'], $where = []): array; public function getCurrencyListRate($currencyIds, $field = ['id', 'currency_id', 'rate_val'], $where = []): array;
} }
\ No newline at end of file
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 姜克保 * User: 姜克保
* Date: 2020/5/20 * Date: 2020/5/20
* Time: 15:48 * Time: 15:48
*/ */
namespace Meibuyu\Micro\Service\Interfaces\DingTalk; namespace Meibuyu\Micro\Service\Interfaces\DingTalk;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Message\DingTalk\DingDepartmentServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Message\DingTalk\DingDepartmentServiceInterface
*/ */
interface DingDepartmentServiceInterface interface DingDepartmentServiceInterface
{ {
/** /**
* 获取部门列表 * 获取部门列表
* @param null $id 部门id * @param null $id 部门id
* @param bool $isFetchChild 是否获取子部门 * @param bool $isFetchChild 是否获取子部门
* @param null $lang * @param null $lang
* @return array * @return array
*/ */
public function getDepartmentList($id = null, $isFetchChild = false, $lang = null): array; public function getDepartmentList($id = null, $isFetchChild = false, $lang = null): array;
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 姜克保 * User: 姜克保
* Date: 2020/5/20 * Date: 2020/5/20
* Time: 15:48 * Time: 15:48
*/ */
namespace Meibuyu\Micro\Service\Interfaces\DingTalk; namespace Meibuyu\Micro\Service\Interfaces\DingTalk;
use phpDocumentor\Reflection\Types\Mixed_; use phpDocumentor\Reflection\Types\Mixed_;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Message\DingTalk\DingMessageServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Message\DingTalk\DingMessageServiceInterface
*/ */
interface DingMessageServiceInterface interface DingMessageServiceInterface
{ {
/** /**
* 发送普通消息 * 发送普通消息
* *
* @param string $sender 消息发送者 userId * @param string $sender 消息发送者 userId
* @param string $cid 群会话或者个人会话的id,通过JSAPI接口唤起联系人界面选择会话获取会话cid;小程序参考获取会话信息,H5微应用参考获取会话信息 * @param string $cid 群会话或者个人会话的id,通过JSAPI接口唤起联系人界面选择会话获取会话cid;小程序参考获取会话信息,H5微应用参考获取会话信息
* @param array $message 消息内容,消息类型和样例可参考“消息类型与数据格式”文档。最长不超过2048个字节 * @param array $message 消息内容,消息类型和样例可参考“消息类型与数据格式”文档。最长不超过2048个字节
* *
* @return mixed * @return mixed
*/ */
public function sendGeneralMessage($sender, $cid, $message); public function sendGeneralMessage($sender, $cid, $message);
/** /**
* 发送工作通知消息 * 发送工作通知消息
* @param array $params * @param array $params
* 发送给多个用户userid_list userid用逗号分隔 * 发送给多个用户userid_list userid用逗号分隔
* ['userid_list' => "016740060622772430,251201234433774424",'msg' => '钉钉消息测试','msgtype' => 'text']; * ['userid_list' => "016740060622772430,251201234433774424",'msg' => '钉钉消息测试','msgtype' => 'text'];
* 发送给所有人 * 发送给所有人
* ['dept_id_list' => "1,2",'msg' => '钉钉消息测试','msgtype' => 'text']; * ['dept_id_list' => "1,2",'msg' => '钉钉消息测试','msgtype' => 'text'];
* 发送给多个部门 部门用逗号分隔 * 发送给多个部门 部门用逗号分隔
* ['to_all_user' => "true",'msg' => '钉钉消息测试','msgtype' => 'text']; * ['to_all_user' => "true",'msg' => '钉钉消息测试','msgtype' => 'text'];
* @return mixed * @return mixed
*/ */
public function sendCorporationMessage($params); public function sendCorporationMessage($params);
/** /**
* @param int $taskId * @param int $taskId
* *
* @return mixed * @return mixed
*/ */
public function corporationMessage($taskId); public function corporationMessage($taskId);
/** /**
* 发送text钉钉消息 * 发送text钉钉消息
* @param integer $templateId 模板id * @param integer $templateId 模板id
* @param array $replace 替换内容(注意顺序) * @param array $replace 替换内容(注意顺序)
* @param array $userIds 用户id(这个是微服务用户的id) * @param array $userIds 用户id(这个是微服务用户的id)
* @return mixed * @return mixed
*/ */
public function sendTextMessage($templateId, $replace, $userIds); public function sendTextMessage($templateId, $replace, $userIds);
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 姜克保 * User: 姜克保
* Date: 2020/5/20 * Date: 2020/5/20
* Time: 15:48 * Time: 15:48
*/ */
namespace Meibuyu\Micro\Service\Interfaces\DingTalk; namespace Meibuyu\Micro\Service\Interfaces\DingTalk;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Message\DingTalk\DingUserServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Message\DingTalk\DingUserServiceInterface
*/ */
interface DingUserServiceInterface interface DingUserServiceInterface
{ {
/** 通过用户id获取单个用户信息 /** 通过用户id获取单个用户信息
* @param string $ding_user_id 钉钉用户id * @param string $ding_user_id 钉钉用户id
* @return array 钉钉用户信息 * @return array 钉钉用户信息
*/ */
public function getByDingUserId($ding_user_id): array; public function getByDingUserId($ding_user_id): array;
/** /**
* 获取部门用户列表 * 获取部门用户列表
* @return array * @return array
*/ */
public function getDingUserLists(): array; public function getDingUserLists(): array;
/** /**
* 通过临时授权码获取用户信息 * 通过临时授权码获取用户信息
* @param string $code 临时授权码 * @param string $code 临时授权码
* @return array * @return array
*/ */
public function getDingUserByTempCode($code): array; public function getDingUserByTempCode($code): array;
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 姜克保 * User: 姜克保
* Date: 2020/5/20 * Date: 2020/5/20
* Time: 15:48 * Time: 15:48
*/ */
namespace Meibuyu\Micro\Service\Interfaces; namespace Meibuyu\Micro\Service\Interfaces;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Store\DispatchPlanServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Store\DispatchPlanServiceInterface
*/ */
interface DispatchPlanServiceInterface interface DispatchPlanServiceInterface
{ {
/** /**
* 返回发货计划存在的仓库子产品id * 返回发货计划存在的仓库子产品id
* @param array $idList 仓库子产品id * @param array $idList 仓库子产品id
* @return array * @return array
*/ */
public function getExistProductChildIds(array $idList): array; public function getExistProductChildIds(array $idList): array;
/** /**
* 返回发货计划存在的平台子产品id * 返回发货计划存在的平台子产品id
* @param array $idList * @param array $idList
* @return array * @return array
*/ */
public function getExistPlatformProductChildIds(array $idList): array; public function getExistPlatformProductChildIds(array $idList): array;
} }
<?php <?php
namespace Meibuyu\Micro\Service\Interfaces\File; namespace Meibuyu\Micro\Service\Interfaces\File;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\File\FileServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\File\FileServiceInterface
*/ */
interface FileServiceInterface interface FileServiceInterface
{ {
/** /**
* @param string $type 类型编码 0001 * @param string $type 类型编码 0001
* @param integer $number 生成条形码数量 100 * @param integer $number 生成条形码数量 100
* @return mixed * @return mixed
*/ */
public function generateBarCode($type, $number); public function generateBarCode($type, $number);
} }
\ No newline at end of file
<?php <?php
namespace Meibuyu\Micro\Service\Interfaces\Flow; namespace Meibuyu\Micro\Service\Interfaces\Flow;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Flow\GetConnectModuleServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Flow\GetConnectModuleServiceInterface
*/ */
interface GetConnectModuleServiceInterface interface GetConnectModuleServiceInterface
{ {
/** /**
*通过通道名称获取process_id *通过通道名称获取process_id
* @param string $channel 通道名 * @param string $channel 通道名
* @return mixed * @return mixed
*/ */
public function getConnectModule($channel); public function getConnectModule($channel);
} }
\ No newline at end of file
<?php <?php
namespace Meibuyu\Micro\Service\Interfaces\Flow; namespace Meibuyu\Micro\Service\Interfaces\Flow;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Flow\ProcessFormServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Flow\ProcessFormServiceInterface
*/ */
interface ProcessFormServiceInterface interface ProcessFormServiceInterface
{ {
/** /**
* 创建流程申请 * 创建流程申请
* @param integer $processId 流程id * @param integer $processId 流程id
* @param string $url 表单图片地址 * @param string $url 表单图片地址
* @param array $data 表单详细内容 * @param array $data 表单详细内容
* @param string $user 当前用户信息 * @param string $user 当前用户信息
* @return mixed * @return mixed
*/ */
public function createProcessForm($processId, $url, array $data, $user); public function createProcessForm($processId, $url, array $data, $user);
/** /**
* @param array $ApplyId 申请的id * @param array $ApplyId 申请的id
* @param string $operate 操作:'agree'同意 'turnDown'驳回 'plug'撤回 * @param string $operate 操作:'agree'同意 'turnDown'驳回 'plug'撤回
* @return mixed * @return mixed
*/ */
public function operateFlow($ApplyId, $operate); public function operateFlow($ApplyId, $operate);
} }
\ No newline at end of file
<?php <?php
namespace Meibuyu\Micro\Service\Interfaces\Logistics; namespace Meibuyu\Micro\Service\Interfaces\Logistics;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Logistics\LogisticsServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Logistics\LogisticsServiceInterface
*/ */
interface LogisticsServiceInterface interface LogisticsServiceInterface
{ {
/** /**
* 将物流单号推送到物流中心,物流中心会时刻监视运单变化实时推送给订阅模块 * 将物流单号推送到物流中心,物流中心会时刻监视运单变化实时推送给订阅模块
* @param string $module 模块名称 * @param string $module 模块名称
* @param array $logisticsInfo 物流公司信息 $logisticsInfo = [['logistics_code' => '', 'logistics_no' => '']]; * @param array $logisticsInfo 物流公司信息 $logisticsInfo = [['logistics_code' => '', 'logistics_no' => '']];
* @return mixed * @return mixed
*/ */
public function push($module,$logisticsInfo); public function push($module,$logisticsInfo);
/** /**
* 根据物流单号查询物流信息 * 根据物流单号查询物流信息
* @param array $logisticsNo 物流订单号 * @param array $logisticsNo 物流订单号
* @return mixed * @return mixed
*/ */
public function logisticsInfo($logisticsNo); public function logisticsInfo($logisticsNo);
} }
\ No newline at end of file
File mode changed from 100644 to 100755
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: zhaopeng * User: zhaopeng
* Date: 2020/9/5 * Date: 2020/9/5
* Time: 10:09 * Time: 10:09
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Operation; namespace Meibuyu\Micro\Service\Interfaces\Operation;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Operation\OperationServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Operation\OperationServiceInterface
*/ */
interface OperationServiceInterface interface OperationServiceInterface
{ {
/** /**
* 获取销售报表其他数据 * 获取销售报表其他数据
* @param array $conditions 必传条件 site_id team_id start_time end_time * @param array $conditions 必传条件 site_id team_id start_time end_time
* @return mixed * @return mixed
*/ */
public function getBusinessSaleOtherDatum(array $conditions); public function getBusinessSaleOtherDatum(array $conditions);
/** /**
* 获取销售报表其他数据 * 获取销售报表其他数据
* @param array $conditions 必传条件 site_id team_id start_time end_time * @param array $conditions 必传条件 site_id team_id start_time end_time
* @return mixed * @return mixed
*/ */
public function getBusinessSaleOtherDatumRmb(array $conditions); public function getBusinessSaleOtherDatumRmb(array $conditions);
} }
\ No newline at end of file
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 姜克保 * User: 姜克保
* Date: 2020/5/20 * Date: 2020/5/20
* Time: 15:48 * Time: 15:48
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Order; namespace Meibuyu\Micro\Service\Interfaces\Order;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Order\ShopifyOrderServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Order\ShopifyOrderServiceInterface
*/ */
interface ShopifyOrderServiceInterface interface ShopifyOrderServiceInterface
{ {
/** /**
* shopify 推送订单信息 * shopify 推送订单信息
* @param string $topic 动作 * @param string $topic 动作
* @param array $array 订单信息 * @param array $array 订单信息
* @param array $shopifySite 站点信息 * @param array $shopifySite 站点信息
* @return mixed * @return mixed
*/ */
public function pushOrder($topic, array $array = [], array $shopifySite = []); public function pushOrder($topic, array $array = [], array $shopifySite = []);
} }
<?php <?php
namespace Meibuyu\Micro\Service\Interfaces\Order; namespace Meibuyu\Micro\Service\Interfaces\Order;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Order\StockUpServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Order\StockUpServiceInterface
*/ */
interface StockUpServiceInterface interface StockUpServiceInterface
{ {
/** /**
*自动备货入库后改变备货单状态为已入库 *自动备货入库后改变备货单状态为已入库
* @param $stockNo * @param $stockNo
* @return mixed * @return mixed
*/ */
public function stockIntoUpdateStatus($stockNo):bool; public function stockIntoUpdateStatus($stockNo):bool;
/** /**
* 跟进物流单号 * 跟进物流单号
* @param $logisticsNo * @param $logisticsNo
* @return array * @return array
*/ */
public function getStockUpInfoByLogisticsNo($logisticsNo):array; public function getStockUpInfoByLogisticsNo($logisticsNo):array;
/** /**
* *
* @param $sourceNo * @param $sourceNo
* @return array * @return array
*/ */
public function getStockUpInfoByOrderNo($sourceNo):array; public function getStockUpInfoByOrderNo($sourceNo):array;
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: zhaopeng * User: zhaopeng
* Date: 2020/9/1 * Date: 2020/9/1
* Time: 10:09 * Time: 10:09
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Order; namespace Meibuyu\Micro\Service\Interfaces\Order;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Order\SubOrderServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Order\SubOrderServiceInterface
*/ */
interface SubOrderServiceInterface interface SubOrderServiceInterface
{ {
/** /**
* @param int $id * @param int $id
* @param array $column 需要查询的字段 * @param array $column 需要查询的字段
* @param array $relation 需要的子订单关联关系可传入['order','order_product'] * @param array $relation 需要的子订单关联关系可传入['order','order_product']
* @return array | null * @return array | null
*/ */
public function getById(int $id, array $column = ['*'], array $relation = []): array; public function getById(int $id, array $column = ['*'], array $relation = []): array;
/** /**
* *
* @param array $idList 子订单的ID 数组[1,2,3] * @param array $idList 子订单的ID 数组[1,2,3]
* @param array $column 需要查询字段 * @param array $column 需要查询字段
* @param array $relation 需要的关联关系可传入['order','order_product'] * @param array $relation 需要的关联关系可传入['order','order_product']
* @return array | null * @return array | null
*/ */
public function getByIdList(array $idList, array $column = ['*'], array $relation = []): array; public function getByIdList(array $idList, array $column = ['*'], array $relation = []): array;
/** /**
* @param array $idList 需要改变发货状态的子订单ID数组 * @param array $idList 需要改变发货状态的子订单ID数组
* @param int $status 需要改变的发货状态ID 1 待发货 2 已发货 3 已签收 4 已取消 * @param int $status 需要改变的发货状态ID 1 待发货 2 已发货 3 已签收 4 已取消
* @return bool * @return bool
*/ */
public function updateSubOrderShipStatus(array $idList, int $status): bool; public function updateSubOrderShipStatus(array $idList, int $status): bool;
/** /**
* 需要改变的子订单id * 需要改变的子订单id
* @param int $id * @param int $id
* @return bool * @return bool
*/ */
public function StockIntoUpdateSubOrderStatus(int $id): bool; public function StockIntoUpdateSubOrderStatus(int $id): bool;
/** /**
* description:通过来源单号获取生产工厂 * description:通过来源单号获取生产工厂
* author: fuyunnan * author: fuyunnan
* @param * @param
* @return array * @return array
* @throws * @throws
* Date: 2020/10/29 * Date: 2020/10/29
*/ */
public function getBySourcesFactory($sources): array; public function getBySourcesFactory($sources): array;
/** /**
* *
* @param array $source 来源单号数组 * @param array $source 来源单号数组
* @return array * @return array
*/ */
public function getBySourceSite($source): array; public function getBySourceSite($source): array;
/** /**
* 订单采购完成 修改子订单信息 ---1688采购系统使用 * 订单采购完成 修改子订单信息 ---1688采购系统使用
* @param $data //修改参数数组(二维数组) * @param $data //修改参数数组(二维数组)
* 参数字段:$data = [ * 参数字段:$data = [
* [ * [
* 'sub_order_no'=>oa子订单编号 * 'sub_order_no'=>oa子订单编号
* 'supplier_name'=>供应商, * 'supplier_name'=>供应商,
* 'purchase_price'=>采购总价, * 'purchase_price'=>采购总价,
* 'platform_order'=>'采购平台订单号', * 'platform_order'=>'采购平台订单号',
* 'domestic_logistics_no'=>物流单号, * 'domestic_logistics_no'=>物流单号,
* 'domestic_logistics_price'=>物流价格 * 'domestic_logistics_price'=>物流价格
* ], * ],
* [ * [
* 'sub_order_no'=>oa子订单编号 * 'sub_order_no'=>oa子订单编号
* 'supplier_name'=>供应商, * 'supplier_name'=>供应商,
* 'purchase_price'=>采购总价, * 'purchase_price'=>采购总价,
* 'platform_order'=>'采购平台订单号', * 'platform_order'=>'采购平台订单号',
* 'domestic_logistics_no'=>物流单号, * 'domestic_logistics_no'=>物流单号,
* 'domestic_logistics_price'=>物流价格 * 'domestic_logistics_price'=>物流价格
* ] * ]
* ] * ]
* @return bool * @return bool
*/ */
public function purchaseCompleted($data,$type): bool; public function purchaseCompleted($data,$type): bool;
/** /**
* 1688采购异常订单 修改OA子订单状态 * 1688采购异常订单 修改OA子订单状态
* @param $orderId //oa子订单id * @param $orderId //oa子订单id
* @param $errorCode //异常信息 1 取消 2其他 * @param $errorCode //异常信息 1 取消 2其他
* @return array * @return array
*/ */
public function purchaseError($orderId,$errorCode):array ; public function purchaseError($orderId,$errorCode):array ;
/** /**
* 1688采购取消 * 1688采购取消
* @param $orderNo * @param $orderNo
* @param $editData * @param $editData
* @return bool * @return bool
*/ */
public function purchaseCancel($orderNo,$editData = []):bool; public function purchaseCancel($orderNo,$editData = []):bool;
/** /**
* 1688采购 修改oa子订单 * 1688采购 修改oa子订单
* @param $editData * @param $editData
* $editData = [ * $editData = [
* 'logistic_no'=>'需要修改的物流单号' * 'logistic_no'=>'需要修改的物流单号'
* 'logistic_no_new'=>'修改后的物流单号', * 'logistic_no_new'=>'修改后的物流单号',
* 'logistic_price'=>'物流费用', * 'logistic_price'=>'物流费用',
* ] * ]
* @return array * @return array
*/ */
public function purchaseEdit($editData):bool ; public function purchaseEdit($editData):bool ;
/** /**
* 删除物流信息 * 删除物流信息
* @param $data =>[ * @param $data =>[
* 'sub_order_no'=>'子订单号', * 'sub_order_no'=>'子订单号',
* 'logistic_no'=>'物流单号' * 'logistic_no'=>'物流单号'
* ] * ]
* @return bool * @return bool
*/ */
public function purchaseDelete($data):bool; public function purchaseDelete($data):bool;
} }
\ No newline at end of file
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 梁俊杰 * User: 梁俊杰
* Date: 2020/5/15 * Date: 2020/5/15
* Time: 15:07 * Time: 15:07
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Product; namespace Meibuyu\Micro\Service\Interfaces\Product;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\MaterialServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\MaterialServiceInterface
*/ */
interface MaterialServiceInterface interface MaterialServiceInterface
{ {
/** /**
* 获取单个数据 * 获取单个数据
* @param int $id 原料id * @param int $id 原料id
* @param array $columns 原料表的字段,默认显示全部 * @param array $columns 原料表的字段,默认显示全部
* @return array|null * @return array|null
*/ */
public function get($id, array $columns = ['*']); public function get($id, array $columns = ['*']);
/** /**
* 通过id列表获取原料数组 * 通过id列表获取原料数组
* @param array $idList 原料id的列表, 默认去重 * @param array $idList 原料id的列表, 默认去重
* @param array $columns 原料表的字段,默认显示全部 * @param array $columns 原料表的字段,默认显示全部
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
*/ */
public function getByIdList(array $idList, array $columns = ['*']): array; public function getByIdList(array $idList, array $columns = ['*']): array;
/** /**
* 通过内部code列表获取原料列表 * 通过内部code列表获取原料列表
* @param array $codeList 默认去重 * @param array $codeList 默认去重
* @param array $columns * @param array $columns
* @return array 默认keyBy('internal_code') * @return array 默认keyBy('internal_code')
*/ */
public function getByCodeList(array $codeList, array $columns = ['id']); public function getByCodeList(array $codeList, array $columns = ['id']);
/** /**
* 获取指定品名下所有的原料数据 * 获取指定品名下所有的原料数据
* @param array $nameIds 默认去重 * @param array $nameIds 默认去重
* @param array $columns * @param array $columns
* @return array 默认groupBy('material_name_id') * @return array 默认groupBy('material_name_id')
*/ */
public function getListByNameIds(array $nameIds, array $columns = ['*']); public function getListByNameIds(array $nameIds, array $columns = ['*']);
/** /**
* 通过原料品名id列表获取原料品名数组 * 通过原料品名id列表获取原料品名数组
* @param array $idList 原料品名id的列表, 默认去重 * @param array $idList 原料品名id的列表, 默认去重
* @param bool $withMaterials 是否关联原料数据 * @param bool $withMaterials 是否关联原料数据
* @param array $columns 原料品名表的字段,默认显示全部 * @param array $columns 原料品名表的字段,默认显示全部
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
*/ */
public function getMaterialNamesByIdList(array $idList, $withMaterials = false, array $columns = ['*']): array; public function getMaterialNamesByIdList(array $idList, $withMaterials = false, array $columns = ['*']): array;
/** /**
* 获取某原料品类下的所有原料品名 * 获取某原料品类下的所有原料品名
* @param $categoryId * @param $categoryId
* @return array * @return array
*/ */
public function getMaterialNamesByCategoryId($categoryId); public function getMaterialNamesByCategoryId($categoryId);
/** /**
* 判断产品是否绑定原料品名 * 判断产品是否绑定原料品名
* @param $productId * @param $productId
* @return bool * @return bool
*/ */
public function hasProductMaterialNames($productId): bool; public function hasProductMaterialNames($productId): bool;
/** /**
* 获取产品绑定的原料品名 * 获取产品绑定的原料品名
* @param $productId * @param $productId
* @return array keyBy('id') * @return array keyBy('id')
*/ */
public function getProductMaterialNames($productId); public function getProductMaterialNames($productId);
/** /**
* 获取产品对应颜色绑定的原料 * 获取产品对应颜色绑定的原料
* @param $productId * @param $productId
* @param array $colorIds 默认去重 * @param array $colorIds 默认去重
* @param bool $withMaterials * @param bool $withMaterials
* @return array 默认keyBy('color_id') * @return array 默认keyBy('color_id')
*/ */
public function getProductColorMaterials($productId, array $colorIds, $withMaterials = false); public function getProductColorMaterials($productId, array $colorIds, $withMaterials = false);
/** /**
* 获取维护完全原料数量的颜色id * 获取维护完全原料数量的颜色id
* @param $productId * @param $productId
* @return array * @return array
*/ */
public function getFullMaterialCountColorIds($productId); public function getFullMaterialCountColorIds($productId);
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 王源 * User: 王源
* Date: 2020/1/9 * Date: 2020/1/9
* Time: 15:07 * Time: 15:07
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Product; namespace Meibuyu\Micro\Service\Interfaces\Product;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\PlatformProductChildServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\PlatformProductChildServiceInterface
*/ */
interface PlatformProductChildServiceInterface interface PlatformProductChildServiceInterface
{ {
/** /**
* 获取单个数据 * 获取单个数据
* @param int $id 平台产品id * @param int $id 平台产品id
* @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight"] * @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight"]
* @param array $columns 平台子产品表的字段,默认全部字段 * @param array $columns 平台子产品表的字段,默认全部字段
* ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale'] * ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale']
* @return array|null * @return array|null
*/ */
public function get($id, array $relations = [], $columns = ['*']); public function get($id, array $relations = [], $columns = ['*']);
/** /**
* 通过id列表获取平台子产品数组 * 通过id列表获取平台子产品数组
* @param array $idList 平台子产品id的列表, 默认去重 * @param array $idList 平台子产品id的列表, 默认去重
* @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"] * @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"]
* @param array $columns 平台子产品表的字段,默认全部字段 * @param array $columns 平台子产品表的字段,默认全部字段
* ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale'] * ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale']
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
*/ */
public function getByIdList(array $idList, array $relations = [], $columns = ['*']): array; public function getByIdList(array $idList, array $relations = [], $columns = ['*']): array;
/** /**
* 获取单个数据 * 获取单个数据
* @param string $sku 平台子产品sku * @param string $sku 平台子产品sku
* @param int $siteId 平台子产品所属站点 * @param int $siteId 平台子产品所属站点
* @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"] * @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"]
* @param array $columns 平台子产品表的字段,默认全部字段 * @param array $columns 平台子产品表的字段,默认全部字段
* ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale'] * ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale']
* @return array * @return array
*/ */
public function getBySku($sku, $siteId, array $relations = [], $columns = ['*']): array; public function getBySku($sku, $siteId, array $relations = [], $columns = ['*']): array;
/** /**
* 通过sku列表获取平台子产品数组 * 通过sku列表获取平台子产品数组
* @param array $skuList 平台子产品sku的列表, 默认去重 * @param array $skuList 平台子产品sku的列表, 默认去重
* @param int $siteId 平台子产品所属站点 * @param int $siteId 平台子产品所属站点
* @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"] * @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"]
* @param array $columns 平台子产品表的字段,默认全部字段 * @param array $columns 平台子产品表的字段,默认全部字段
* ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale'] * ['id','platform_product_id','product_child_id','platform_product_child_sku','asin','fnsku','is_sale']
* @return array 默认keyBy('platform_product_child_sku') * @return array 默认keyBy('platform_product_child_sku')
*/ */
public function getBySkuList(array $skuList, $siteId, array $relations = [], $columns = ['*']): array; public function getBySkuList(array $skuList, $siteId, array $relations = [], $columns = ['*']): array;
/** /**
* 模糊搜索平台子sku,获取id数组 * 模糊搜索平台子sku,获取id数组
* @param string $childSku 平台子sku * @param string $childSku 平台子sku
* @param array|null $limitIds 限制id数组,不传为不限制 * @param array|null $limitIds 限制id数组,不传为不限制
* @return array * @return array
*/ */
public function getIdsByChildSku(string $childSku, array $limitIds = null); public function getIdsByChildSku(string $childSku, array $limitIds = null);
/** /**
* 获取仓库主sku对应的平台主sku * 获取仓库主sku对应的平台主sku
* @param array $productChildIds 已去重 * @param array $productChildIds 已去重
* @param null $siteId 指定站点id, 不传或传null,获取全部数据 * @param null $siteId 指定站点id, 不传或传null,获取全部数据
* @param array $columns * @param array $columns
* @return array * @return array
*/ */
public function getListByProductChildIds(array $productChildIds, $siteId = null, array $columns = ['*']); public function getListByProductChildIds(array $productChildIds, $siteId = null, array $columns = ['*']);
/** /**
* 通过仓库产品id获取平台子产品数组 * 通过仓库产品id获取平台子产品数组
* @param $productId * @param $productId
* @param null $siteId * @param null $siteId
* @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"] * @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"]
* @param array $columns * @param array $columns
* @return array * @return array
*/ */
public function getListByProductIds($productId, $siteId = null, array $relations = [], $columns = ['*']); public function getListByProductIds($productId, $siteId = null, array $relations = [], $columns = ['*']);
/** /**
* 通过颜色和尺码id获取平台子产品数组 * 通过颜色和尺码id获取平台子产品数组
* @param $productId * @param $productId
* @param $colorId * @param $colorId
* @param $sizeId * @param $sizeId
* @param $siteId * @param $siteId
* @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"] * @param array $relations 平台子产品的关联关系,支持:["platform_product","product_child","weight","packs"]
* @return array * @return array
* @author Zero * @author Zero
*/ */
public function getListByColorSizeIds($productId, $colorId, $sizeId, $siteId, $relations = []); public function getListByColorSizeIds($productId, $colorId, $sizeId, $siteId, $relations = []);
/** /**
* 通过颜色和尺码id获取平台组合子产品数组 * 通过颜色和尺码id获取平台组合子产品数组
* @param $productId * @param $productId
* @param $siteId * @param $siteId
* @param array $colorIds * @param array $colorIds
* @param $sizeId * @param $sizeId
* @return array * @return array
* @author Zero * @author Zero
*/ */
public function getPackListByColorSizeIds($productId, $siteId, $colorIds, $sizeId); public function getPackListByColorSizeIds($productId, $siteId, $colorIds, $sizeId);
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 王源 * User: 王源
* Date: 2020/1/9 * Date: 2020/1/9
* Time: 15:07 * Time: 15:07
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Product; namespace Meibuyu\Micro\Service\Interfaces\Product;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\PlatformProductServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\PlatformProductServiceInterface
*/ */
interface PlatformProductServiceInterface interface PlatformProductServiceInterface
{ {
/** /**
* 获取单个数据 * 获取单个数据
* @param int $id 平台产品id * @param int $id 平台产品id
* @param array $relations 平台产品的关联关系, * @param array $relations 平台产品的关联关系,
* 支持:["status","product","amazon_warehouse","platform_product_children","brand","category","ingredient","product_name","images","price_info","property"] * 支持:["status","product","amazon_warehouse","platform_product_children","brand","category","ingredient","product_name","images","price_info","property"]
* @param array $columns 平台产品表的字段,默认全部字段 * @param array $columns 平台产品表的字段,默认全部字段
* ['id', 'sku', 'product_id', 'name', 'team_id', 'site_id', 'price', 'currency_id', 'platform_product_status_id', 'creator_id', 'asin', 'amazon_warehouse_id', 'info_completed'] * ['id', 'sku', 'product_id', 'name', 'team_id', 'site_id', 'price', 'currency_id', 'platform_product_status_id', 'creator_id', 'asin', 'amazon_warehouse_id', 'info_completed']
* @return array|null * @return array|null
*/ */
public function get($id, array $relations = [], $columns = ['*']); public function get($id, array $relations = [], $columns = ['*']);
/** /**
* 通过id列表获取平台产品数组 * 通过id列表获取平台产品数组
* @param array $idList 平台产品id的列表, 默认去重 * @param array $idList 平台产品id的列表, 默认去重
* @param array $relations 平台产品的关联关系, * @param array $relations 平台产品的关联关系,
* 支持:["status","product","amazon_warehouse","platform_product_children","brand","category","ingredient","product_name","images","price_info","property"] * 支持:["status","product","amazon_warehouse","platform_product_children","brand","category","ingredient","product_name","images","price_info","property"]
* @param array $columns 平台产品表的字段,默认全部字段 * @param array $columns 平台产品表的字段,默认全部字段
* ['id', 'sku', 'product_id', 'name', 'team_id', 'site_id', 'price', 'currency_id', 'platform_product_status_id', 'creator_id', 'asin', 'amazon_warehouse_id', 'info_completed'] * ['id', 'sku', 'product_id', 'name', 'team_id', 'site_id', 'price', 'currency_id', 'platform_product_status_id', 'creator_id', 'asin', 'amazon_warehouse_id', 'info_completed']
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
*/ */
public function getByIdList(array $idList, array $relations = [], $columns = ['*']): array; public function getByIdList(array $idList, array $relations = [], $columns = ['*']): array;
/** /**
* 获取申报要素数据 * 获取申报要素数据
* @param array $idList * @param array $idList
* @param bool $groupByFlag * @param bool $groupByFlag
* @return array * @return array
*/ */
public function getWithPoint(array $idList, $groupByFlag = false); public function getWithPoint(array $idList, $groupByFlag = false);
/** /**
* 获取全部亚马逊仓库 * 获取全部亚马逊仓库
* @return array * @return array
*/ */
public function amazonWarehouses(); public function amazonWarehouses();
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 王源 * User: 王源
* Date: 2020/1/9 * Date: 2020/1/9
* Time: 15:07 * Time: 15:07
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Product; namespace Meibuyu\Micro\Service\Interfaces\Product;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\ProductChildServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\ProductChildServiceInterface
*/ */
interface ProductChildServiceInterface interface ProductChildServiceInterface
{ {
/** /**
* 获取单个数据 * 获取单个数据
* @param int $id 子SKU id * @param int $id 子SKU id
* @param array $columns 子SKU表的字段,默认显示全部 * @param array $columns 子SKU表的字段,默认显示全部
* @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost', 'weight', 'packs'] * @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost', 'weight', 'packs']
* @return array|null * @return array|null
*/ */
public function get($id, array $columns = ['*'], array $relations = []); public function get($id, array $columns = ['*'], array $relations = []);
/** /**
* 通过id列表获取产品数组 * 通过id列表获取产品数组
* @param array $idList 子SKUid的列表, 默认去重 * @param array $idList 子SKUid的列表, 默认去重
* @param array $columns 子SKU表的字段,默认显示全部 * @param array $columns 子SKU表的字段,默认显示全部
* @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost', 'weight', 'packs'] * @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost', 'weight', 'packs']
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
*/ */
public function getByIdList(array $idList, array $columns = ['*'], array $relations = []): array; public function getByIdList(array $idList, array $columns = ['*'], array $relations = []): array;
/** /**
* 通过sku列表获取子产品列表 * 通过sku列表获取子产品列表
* @param array $skuList 默认去重 * @param array $skuList 默认去重
* @param array $columns 子SKU表的字段,默认返回id * @param array $columns 子SKU表的字段,默认返回id
* @param array $relations 子SKU的关联关系,可传入['color', 'size','brand', 'category', 'product_name', 'images', 'cost', 'weight', 'packs'] * @param array $relations 子SKU的关联关系,可传入['color', 'size','brand', 'category', 'product_name', 'images', 'cost', 'weight', 'packs']
* @return array 默认keyBy('child_sku') * @return array 默认keyBy('child_sku')
*/ */
public function getListBySkuList(array $skuList, array $columns = ['id'], array $relations = []); public function getListBySkuList(array $skuList, array $columns = ['id'], array $relations = []);
/** /**
* 获取全部尺码列表 * 获取全部尺码列表
* @param array $columns 默认['id', 'name'] * @param array $columns 默认['id', 'name']
* @return array * @return array
*/ */
public function sizes(array $columns = ['id', 'name']): array; public function sizes(array $columns = ['id', 'name']): array;
/** /**
* 获取全部颜色列表 * 获取全部颜色列表
* @param array $columns 默认['id', 'code', 'cn_name', 'en_name'] * @param array $columns 默认['id', 'code', 'cn_name', 'en_name']
* @return array * @return array
*/ */
public function colors(array $columns = ['id', 'code', 'cn_name', 'en_name']): array; public function colors(array $columns = ['id', 'code', 'cn_name', 'en_name']): array;
/** /**
* 通过id数组获取尺码列表 * 通过id数组获取尺码列表
* @param array $ids 默认去重 * @param array $ids 默认去重
* @param array $columns * @param array $columns
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getSizesByIds(array $ids, $columns = ['id', 'name']): array; public function getSizesByIds(array $ids, $columns = ['id', 'name']): array;
/** /**
* 通过id数组获取颜色列表 * 通过id数组获取颜色列表
* @param array $ids 默认去重 * @param array $ids 默认去重
* @param array $columns * @param array $columns
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getColorsByIds(array $ids, array $columns = ['id', 'code', 'cn_name', 'en_name']): array; public function getColorsByIds(array $ids, array $columns = ['id', 'code', 'cn_name', 'en_name']): array;
/** /**
* 通过id获取尺码 * 通过id获取尺码
* @param int $id * @param int $id
* @param array $columns * @param array $columns
* @return array|null * @return array|null
*/ */
public function getSizeById(int $id, $columns = ['id', 'name']); public function getSizeById(int $id, $columns = ['id', 'name']);
/** /**
* 通过id获取颜色 * 通过id获取颜色
* @param int $id * @param int $id
* @param array $columns * @param array $columns
* @return array|null * @return array|null
*/ */
public function getColorById(int $id, array $columns = ['id', 'code', 'cn_name', 'en_name']); public function getColorById(int $id, array $columns = ['id', 'code', 'cn_name', 'en_name']);
/** /**
* 获取某产品下的所有子产品 * 获取某产品下的所有子产品
* @param int $productId * @param int $productId
* @param array $columns * @param array $columns
* @return array * @return array
*/ */
public function getListByProductId(int $productId, $columns = ['id', 'child_sku']); public function getListByProductId(int $productId, $columns = ['id', 'child_sku']);
/** /**
* 模糊搜索仓库子sku,获取id数组 * 模糊搜索仓库子sku,获取id数组
* @param string $childSku 仓库子sku * @param string $childSku 仓库子sku
* @param array|null $limitIds 限制id数组,不传为不限制 * @param array|null $limitIds 限制id数组,不传为不限制
* @return array * @return array
*/ */
public function getIdsByChildSku(string $childSku, array $limitIds = null); public function getIdsByChildSku(string $childSku, array $limitIds = null);
/** /**
* 根据主sku品类id获取仓库子sku的id数组 * 根据主sku品类id获取仓库子sku的id数组
* @param int $categoryId * @param int $categoryId
* @param int|null $limit * @param int|null $limit
* @return array * @return array
* @author Zero * @author Zero
*/ */
public function getIdsByCategoryId(int $categoryId, int $limit = null); public function getIdsByCategoryId(int $categoryId, int $limit = null);
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 王源 * User: 王源
* Date: 2020/1/9 * Date: 2020/1/9
* Time: 15:07 * Time: 15:07
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Product; namespace Meibuyu\Micro\Service\Interfaces\Product;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\ProductServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\ProductServiceInterface
*/ */
interface ProductServiceInterface interface ProductServiceInterface
{ {
/** /**
* 获取单个数据 * 获取单个数据
* @param int $id 产品id * @param int $id 产品id
* @param array $relations 产品的关联关系,支持:["brand","category","ingredient","product_name","status","type","images","price_info","product_children"] * @param array $relations 产品的关联关系,支持:["brand","category","ingredient","product_name","status","type","images","price_info","product_children"]
* @param array $columns 产品表的字段,默认 * @param array $columns 产品表的字段,默认
* ['id', 'sku', 'name', 'en_name', 'brand_id', 'team_id', 'hs_code', 'origin_country_id', 'production_address', * ['id', 'sku', 'name', 'en_name', 'brand_id', 'team_id', 'hs_code', 'origin_country_id', 'production_address',
* 'unit', 'category_id', 'ingredient_id', 'product_name_id', 'type_id', 'status_id', 'style', 'info_completed' * 'unit', 'category_id', 'ingredient_id', 'product_name_id', 'type_id', 'status_id', 'style', 'info_completed'
* , 'bar_code', 'bar_code_image', 'creator_id', 'hot'] * , 'bar_code', 'bar_code_image', 'creator_id', 'hot']
* @return array|null * @return array|null
*/ */
public function get($id, array $relations = [], array $columns = ['*']); public function get($id, array $relations = [], array $columns = ['*']);
/** /**
* 通过id列表获取产品数组 * 通过id列表获取产品数组
* @param array $idList 产品id的列表, 默认去重 * @param array $idList 产品id的列表, 默认去重
* @param array $relations 产品的关联关系,支持["brand","category","ingredient","product_name","status","type","images","price_info","product_children"] * @param array $relations 产品的关联关系,支持["brand","category","ingredient","product_name","status","type","images","price_info","product_children"]
* @param array $columns 产品表的字段,默认['id', 'sku', 'name', 'en_name', 'brand_id' * @param array $columns 产品表的字段,默认['id', 'sku', 'name', 'en_name', 'brand_id'
* , 'team_id', 'hs_code', 'origin_country_id', 'production_address', 'unit', 'category_id' * , 'team_id', 'hs_code', 'origin_country_id', 'production_address', 'unit', 'category_id'
* , 'ingredient_id', 'product_name_id', 'type_id', 'status_id', 'style', 'info_completed' * , 'ingredient_id', 'product_name_id', 'type_id', 'status_id', 'style', 'info_completed'
* , 'bar_code', 'bar_code_image', 'creator_id', 'hot'] * , 'bar_code', 'bar_code_image', 'creator_id', 'hot']
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
*/ */
public function getByIdList(array $idList, array $relations = [], array $columns = ['*']): array; public function getByIdList(array $idList, array $relations = [], array $columns = ['*']): array;
/** /**
* 通过sku列表获取产品列表 * 通过sku列表获取产品列表
* @param array $skuList 默认去重 * @param array $skuList 默认去重
* @param array $relations 产品的关联关系,可传入['color', 'size','brand', 'category', 'product_name', 'images', 'cost', 'weight'] * @param array $relations 产品的关联关系,可传入['color', 'size','brand', 'category', 'product_name', 'images', 'cost', 'weight']
* @param array $columns 产品表的字段,默认返回id * @param array $columns 产品表的字段,默认返回id
* @return array 默认keyBy('sku') * @return array 默认keyBy('sku')
*/ */
public function getListBySkuList(array $skuList, array $relations = [], array $columns = ['id']); public function getListBySkuList(array $skuList, array $relations = [], array $columns = ['id']);
/** /**
* 获取全部品类列表 * 获取全部品类列表
* @param bool $asTree 是否作为树返回 * @param bool $asTree 是否作为树返回
* @param array $columns 默认['id', 'name', 'parent_id'] * @param array $columns 默认['id', 'name', 'parent_id']
* @return array * @return array
*/ */
public function categories($asTree = false, array $columns = ['id', 'name', 'parent_id']): array; public function categories($asTree = false, array $columns = ['id', 'name', 'parent_id']): array;
/** /**
* 获取全部品牌列表 * 获取全部品牌列表
* @param array $columns 默认['id', 'name'] * @param array $columns 默认['id', 'name']
* @return array * @return array
*/ */
public function brands(array $columns = ['id', 'name']): array; public function brands(array $columns = ['id', 'name']): array;
/** /**
* 获取全部报关品名列表 * 获取全部报关品名列表
* @param array $columns 默认['id', 'name','en_name'] * @param array $columns 默认['id', 'name','en_name']
* @return array * @return array
*/ */
public function productNames(array $columns = ['id', 'name', 'en_name']): array; public function productNames(array $columns = ['id', 'name', 'en_name']): array;
/** /**
* 获取全部成分列表 * 获取全部成分列表
* @param array $columns 默认['id', 'name'] * @param array $columns 默认['id', 'name']
* @return array * @return array
*/ */
public function ingredients(array $columns = ['id', 'name', 'en_name']): array; public function ingredients(array $columns = ['id', 'name', 'en_name']): array;
/** /**
* 通过id数组获取品类列表 * 通过id数组获取品类列表
* @param array $ids 默认去重 * @param array $ids 默认去重
* @param array $columns * @param array $columns
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getCategoriesByIds(array $ids, array $columns = ['id', 'name', 'parent_id']): array; public function getCategoriesByIds(array $ids, array $columns = ['id', 'name', 'parent_id']): array;
/** /**
* 通过id数组获取品名列表 * 通过id数组获取品名列表
* @param array $ids 默认去重 * @param array $ids 默认去重
* @param array $columns * @param array $columns
* @param array $relations ['report_points'] * @param array $relations ['report_points']
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getProductNamesByIds(array $ids, array $columns = ['id', 'name', 'en_name'], array $relations = []): array; public function getProductNamesByIds(array $ids, array $columns = ['id', 'name', 'en_name'], array $relations = []): array;
/** /**
* 通过id获取品类 * 通过id获取品类
* @param int $id * @param int $id
* @param array $columns * @param array $columns
* @return array|null * @return array|null
*/ */
public function getCategoryById(int $id, array $columns = ['id', 'name', 'parent_id']); public function getCategoryById(int $id, array $columns = ['id', 'name', 'parent_id']);
/** /**
* 通过id获取品名 * 通过id获取品名
* @param int $id * @param int $id
* @param array $columns * @param array $columns
* @param array $relations ['report_points'] * @param array $relations ['report_points']
* @return array|null * @return array|null
*/ */
public function getProductNameById(int $id, array $columns = ['id', 'name', 'en_name'], array $relations = []); public function getProductNameById(int $id, array $columns = ['id', 'name', 'en_name'], array $relations = []);
/** /**
* 通过id数组获取申报要素列表 * 通过id数组获取申报要素列表
* @param array $ids 默认去重 * @param array $ids 默认去重
* @param array $columns * @param array $columns
* @param array $relations ['product_name', 'ingredient'] * @param array $relations ['product_name', 'ingredient']
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getReportPointsByIds(array $ids, array $relations = [], array $columns = ['id', 'hs_code', 'point']): array; public function getReportPointsByIds(array $ids, array $relations = [], array $columns = ['id', 'hs_code', 'point']): array;
/** /**
* 通过id获取申报要素 * 通过id获取申报要素
* @param int $id * @param int $id
* @param array $columns * @param array $columns
* @param array $relations ['product_name', 'ingredient'] * @param array $relations ['product_name', 'ingredient']
* @return array|null * @return array|null
*/ */
public function getReportPointById(int $id, array $relations = [], array $columns = ['id', 'hs_code', 'point']); public function getReportPointById(int $id, array $relations = [], array $columns = ['id', 'hs_code', 'point']);
/** /**
* 获取申报要素数据 * 获取申报要素数据
* @param array $idList 默认去重 * @param array $idList 默认去重
* @param bool $groupByFlag * @param bool $groupByFlag
* @return array keyBy('id') * @return array keyBy('id')
*/ */
public function getWithPoint(array $idList, $groupByFlag = false); public function getWithPoint(array $idList, $groupByFlag = false);
/** /**
* 获取全部申报要素列表 * 获取全部申报要素列表
* @param array $columns 默认['*'] * @param array $columns 默认['*']
* @return array * @return array
*/ */
public function reportPoints(array $columns = ['*']): array; public function reportPoints(array $columns = ['*']): array;
/** /**
* 通过产品id获取维护的所有尺码 * 通过产品id获取维护的所有尺码
* @param $id * @param $id
* @return array * @return array
* @author Zero * @author Zero
*/ */
public function getSizesById($id): array; public function getSizesById($id): array;
/** /**
* 完成产品审批 * 完成产品审批
* @param $data * @param $data
* @author Zero * @author Zero
*/ */
public function downApprove($data); public function downApprove($data);
/** /**
* 检查产品是否同时维护工艺信息核原料信息 * 检查产品是否同时维护工艺信息核原料信息
* @param * @param
* 参数可以通过id * 参数可以通过id
* @return bool 同时维护true,未同时维护false * @return bool 同时维护true,未同时维护false
* @throws \Meibuyu\Rpc\Exceptions\RpcException * @throws \Meibuyu\Rpc\Exceptions\RpcException
* @author Zero * @author Zero
*/ */
public function checkMaterialCraftById($id); public function checkMaterialCraftById($id);
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: Zero * User: Zero
* Date: 2020/10/12 * Date: 2020/10/12
* Time: 9:39 * Time: 9:39
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Product; namespace Meibuyu\Micro\Service\Interfaces\Product;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\ShopifyProductServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\ShopifyProductServiceInterface
*/ */
interface ShopifyProductServiceInterface interface ShopifyProductServiceInterface
{ {
/** /**
* 通过shopify子产品的shopify_id获取shopify子产品 * 通过shopify子产品的shopify_id获取shopify子产品
* @param array $vids 默认去重 * @param array $vids 默认去重
* @return array 默认keyBy * @return array 默认keyBy
*/ */
public function getChildrenByVids(array $vids): array; public function getChildrenByVids(array $vids): array;
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: Zero * User: Zero
* Date: 2020/10/12 * Date: 2020/10/12
* Time: 9:39 * Time: 9:39
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Product; namespace Meibuyu\Micro\Service\Interfaces\Product;
use Exception; use Exception;
use Meibuyu\Micro\Exceptions\RpcException; use Meibuyu\Micro\Exceptions\RpcException;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\ShopifyServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\ShopifyServiceInterface
*/ */
interface ShopifyServiceInterface interface ShopifyServiceInterface
{ {
/** /**
* 拉取一个shopify订单数据 * 拉取一个shopify订单数据
* @param $orderId * @param $orderId
* @param $shopifySiteId * @param $shopifySiteId
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
public function pullOrder($orderId, $shopifySiteId): array; public function pullOrder($orderId, $shopifySiteId): array;
/** /**
* 通过id列表获取shopify站点数组 * 通过id列表获取shopify站点数组
* @param array $ids shopify站点id数组,默认去重 * @param array $ids shopify站点id数组,默认去重
* @param array $columns shopify站点表字段,默认['name', 'prefix', 'team_id', 'site_id', 'language_id', 'url', 'currency_id'] * @param array $columns shopify站点表字段,默认['name', 'prefix', 'team_id', 'site_id', 'language_id', 'url', 'currency_id']
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
* @author Zero * @author Zero
*/ */
public function getShopifySitesByIds(array $ids, $columns = ['name', 'prefix', 'team_id', 'site_id', 'language_id', 'url', 'currency_id']): array; public function getShopifySitesByIds(array $ids, $columns = ['name', 'prefix', 'team_id', 'site_id', 'language_id', 'url', 'currency_id']): array;
/** /**
* 拉取传入的id之后的shopify订单列表数据,默认50条数据 * 拉取传入的id之后的shopify订单列表数据,默认50条数据
* @param int $sinceId 订单id * @param int $sinceId 订单id
* @param int $shopifySiteId shopify站点id * @param int $shopifySiteId shopify站点id
* @return array * @return array
* @throws Exception * @throws Exception
* @author Zero * @author Zero
*/ */
public function pullOrderList($sinceId, $shopifySiteId): array; public function pullOrderList($sinceId, $shopifySiteId): array;
/** /**
* 更新shopify订单 * 更新shopify订单
* @param int $orderId 订单id * @param int $orderId 订单id
* @param array $params 更新的数据 * @param array $params 更新的数据
* @param int $shopifySiteId shopify站点id * @param int $shopifySiteId shopify站点id
* @return mixed * @return mixed
* @throws RpcException * @throws RpcException
* @author zero * @author zero
*/ */
public function updateOrder($orderId, $params, $shopifySiteId); public function updateOrder($orderId, $params, $shopifySiteId);
/** /**
* 创建shopify订单发货记录 * 创建shopify订单发货记录
* 参数示例: https://shopify.dev/docs/admin-api/rest/reference/shipping-and-fulfillment/fulfillment#create-2020-07 * 参数示例: https://shopify.dev/docs/admin-api/rest/reference/shipping-and-fulfillment/fulfillment#create-2020-07
* location_id不传会默认拿取系统有的数据,拿不到报错 * location_id不传会默认拿取系统有的数据,拿不到报错
* @param int $orderId * @param int $orderId
* @param array $params * @param array $params
* @param int $shopifySiteId * @param int $shopifySiteId
* @return mixed * @return mixed
* @throws RpcException * @throws RpcException
* @author zero * @author zero
*/ */
public function createOrderFulfillment($orderId, $params, $shopifySiteId); public function createOrderFulfillment($orderId, $params, $shopifySiteId);
/** /**
* 更新shopify订单发货物流信息 * 更新shopify订单发货物流信息
* 参数示例: https://shopify.dev/docs/admin-api/rest/reference/shipping-and-fulfillment/fulfillment#update_tracking-2020-07 * 参数示例: https://shopify.dev/docs/admin-api/rest/reference/shipping-and-fulfillment/fulfillment#update_tracking-2020-07
* [ * [
* "notify_customer" => true, * "notify_customer" => true,
* "tracking_info" => [ * "tracking_info" => [
* "number" => "1111", * "number" => "1111",
* "url" => "http://www.my-url.com", * "url" => "http://www.my-url.com",
* "company" => "my-company", * "company" => "my-company",
* ] * ]
* ] * ]
* @param $fulfillmentId * @param $fulfillmentId
* @param $params * @param $params
* @param $shopifySiteId * @param $shopifySiteId
* @return array * @return array
* @throws RpcException * @throws RpcException
* @author zero * @author zero
*/ */
public function updateFulfillmentTracking($fulfillmentId, $params, $shopifySiteId); public function updateFulfillmentTracking($fulfillmentId, $params, $shopifySiteId);
/** /**
* 通过id数组获取shopify的location数据 * 通过id数组获取shopify的location数据
* @param $ids * @param $ids
* @param string[] $columns * @param string[] $columns
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
* @author zero * @author zero
*/ */
public function getLocationsByIds($ids, $columns = ['*']); public function getLocationsByIds($ids, $columns = ['*']);
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 王源 * User: 王源
* Date: 2020/1/9 * Date: 2020/1/9
* Time: 15:07 * Time: 15:07
*/ */
namespace Meibuyu\Micro\Service\Interfaces; namespace Meibuyu\Micro\Service\Interfaces;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\ProductChildServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Product\ProductChildServiceInterface
*/ */
interface ProductChildServiceInterface interface ProductChildServiceInterface
{ {
/** /**
* 获取单个数据 * 获取单个数据
* @param int $id 子SKU id * @param int $id 子SKU id
* @param array $columns 子SKU表的字段,默认显示全部 * @param array $columns 子SKU表的字段,默认显示全部
* @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost'] * @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost']
* @return array|null * @return array|null
*/ */
public function get($id, array $columns = ['*'], array $relations = []); public function get($id, array $columns = ['*'], array $relations = []);
/** /**
* 通过id列表获取产品数组 * 通过id列表获取产品数组
* @param array $idList 子SKUid的列表, 默认去重 * @param array $idList 子SKUid的列表, 默认去重
* @param array $columns 子SKU表的字段,默认显示全部 * @param array $columns 子SKU表的字段,默认显示全部
* @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost'] * @param array $relations 子SKU的关联关系,可传入['brand', 'category', 'product_name', 'images', 'cost']
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
*/ */
public function getByIdList(array $idList, array $columns = ['*'], array $relations = []): array; public function getByIdList(array $idList, array $columns = ['*'], array $relations = []): array;
/** /**
* 通过sku列表获取子产品列表 * 通过sku列表获取子产品列表
* @param array $skuList 默认去重 * @param array $skuList 默认去重
* @param array $columns * @param array $columns
* @return array 默认keyBy('child_sku') * @return array 默认keyBy('child_sku')
*/ */
public function getListBySkuList(array $skuList, array $columns = ['id']); public function getListBySkuList(array $skuList, array $columns = ['id']);
} }
<?php <?php
namespace Meibuyu\Micro\Service\Interfaces\Production; namespace Meibuyu\Micro\Service\Interfaces\Production;
use Meibuyu\Micro\Exceptions\HttpResponseException; use Meibuyu\Micro\Exceptions\HttpResponseException;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Production\ProductionServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Production\ProductionServiceInterface
*/ */
interface ProductionServiceInterface interface ProductionServiceInterface
{ {
/** /**
* 生产单批次发货入库回调 * 生产单批次发货入库回调
* @param array $params * @param array $params
* [ * [
* 'production_no' => 'SC20201218-001-001', // 生产单号,必须 * 'production_no' => 'SC20201218-001-001', // 生产单号,必须
* 'auth' => Auth::user(), // 当前用户,必须 * 'auth' => Auth::user(), // 当前用户,必须
* 'warehousing_order' => [ * 'warehousing_order' => [
* 'id' => '123', // 入库单id,必须 * 'id' => '123', // 入库单id,必须
* 'warehousing_no' => 'RK-20200727-001', // 入库单号,必须 * 'warehousing_no' => 'RK-20200727-001', // 入库单号,必须
* 'count' => '123', // 入库数量, 必须 * 'count' => '123', // 入库数量, 必须
* ] * ]
* ] * ]
* @throws HttpResponseException * @throws HttpResponseException
* @author Zero * @author Zero
*/ */
public function warehousingCallback(array $params); public function warehousingCallback(array $params);
/** /**
* 通过入库单id获取相关数据 * 通过入库单id获取相关数据
* @param array $warehousingOrderIds 默认去重 * @param array $warehousingOrderIds 默认去重
* @return array 默认keyBy * @return array 默认keyBy
*/ */
public function getInfoForWarehousingOrder(array $warehousingOrderIds); public function getInfoForWarehousingOrder(array $warehousingOrderIds);
/** /**
* 通过生产单号获取生产单工厂信息 * 通过生产单号获取生产单工厂信息
* @param array $productionNoList 生产单号数组,默认去重 * @param array $productionNoList 生产单号数组,默认去重
* @return array 'production_no' => ['factory_id' => 1, 'factory_name' => 'AL'] * @return array 'production_no' => ['factory_id' => 1, 'factory_name' => 'AL']
* @author Zero * @author Zero
*/ */
public function getFactoryByProductionNoList(array $productionNoList): array; public function getFactoryByProductionNoList(array $productionNoList): array;
/** /**
* 查询备货计划中是否用过仓库子产品 * 查询备货计划中是否用过仓库子产品
* @param array $ids 仓库子产品id数组,默认去重 * @param array $ids 仓库子产品id数组,默认去重
* @return array 返回用过的id数组 * @return array 返回用过的id数组
*/ */
public function searchUsedProductChildId($ids); public function searchUsedProductChildId($ids);
/** /**
* 查询备货计划中是否用过平台子产品 * 查询备货计划中是否用过平台子产品
* @param array $ids 平台子产品id数组,默认去重 * @param array $ids 平台子产品id数组,默认去重
* @return array 返回用过的id数组 * @return array 返回用过的id数组
*/ */
public function searchUsedPlatformProductChildId($ids); public function searchUsedPlatformProductChildId($ids);
} }
<?php <?php
namespace Meibuyu\Micro\Service\Interfaces\Purchase; namespace Meibuyu\Micro\Service\Interfaces\Purchase;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Purchase\PurchaseDoneServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Purchase\PurchaseDoneServiceInterface
*/ */
interface PurchaseDoneServiceInterface interface PurchaseDoneServiceInterface
{ {
/** /**
*通过子订单编号修改采购状态 *通过子订单编号修改采购状态
* @param array $orderIds 子订单编号 ['3333444','12222'] * @param array $orderIds 子订单编号 ['3333444','12222']
* @return mixed * @return mixed
*/ */
public function archivePurchase($orderIds); public function archivePurchase($orderIds);
/** /**
*通过子订单编号通知取消 *通过子订单编号通知取消
* @param array $orderIds 子订单编号 ['3333444','12222'] * @param array $orderIds 子订单编号 ['3333444','12222']
* @return mixed * @return mixed
*/ */
public function noticeToCancel($orderIds); public function noticeToCancel($orderIds);
/** /**
* 传输产品规格 * 传输产品规格
* @param $data ['order_id'=>'子订单编号','order_standard'=>'产品规格'] * @param $data ['order_id'=>'子订单编号','order_standard'=>'产品规格']
* @return mixed * @return mixed
*/ */
public function productStandard($data); public function productStandard($data);
/** /**
* 通过子订单编号查询状态 * 通过子订单编号查询状态
* @param array $orderIds 子订单编号 ['3333444','12222'] * @param array $orderIds 子订单编号 ['3333444','12222']
* @return mixed * @return mixed
*/ */
public function getOrderStatus($orderIds); public function getOrderStatus($orderIds);
} }
\ No newline at end of file
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: Zero * User: Zero
* Date: 2021/06/11 * Date: 2021/06/11
* Time: 14:22:52 * Time: 14:22:52
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Purchase; namespace Meibuyu\Micro\Service\Interfaces\Purchase;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Purchase\PurchaseTaskServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Purchase\PurchaseTaskServiceInterface
*/ */
interface PurchaseTaskServiceInterface interface PurchaseTaskServiceInterface
{ {
/** /**
* 为订单提供获取采购数据 * 为订单提供获取采购数据
* @param array $noList * @param array $noList
* @return array * @return array
* @author Zero * @author Zero
*/ */
public function infoForOrder(array $noList); public function infoForOrder(array $noList);
/** /**
* 通知取消 * 通知取消
* @param array $data * @param array $data
* [ * [
* 'source_id' => '来源id', * 'source_id' => '来源id',
* 'notice_cancel_reason' => '通知取消原因', * 'notice_cancel_reason' => '通知取消原因',
* 'type' => 1 // 1(订单采购); 2(备货采购); 3(样品采购) * 'type' => 1 // 1(订单采购); 2(备货采购); 3(样品采购)
* 'auth' => Auth::user() // 当前用户 * 'auth' => Auth::user() // 当前用户
* ] * ]
* @return bool * @return bool
* @throws \Meibuyu\Micro\Exceptions\RpcException * @throws \Meibuyu\Micro\Exceptions\RpcException
* @author Zero * @author Zero
*/ */
public function noticeCancel(array $data); public function noticeCancel(array $data);
/** /**
* 更新产品数据 * 更新产品数据
* @param mixed $sourceId 来源id * @param mixed $sourceId 来源id
* @param array $data 要更新的数据如['specification', 'remark']等 * @param array $data 要更新的数据如['specification', 'remark']等
* @param int $type 采购类型,默认为订单采购,可传参数[1(订单采购); 2(备货采购); 3(样品采购)] * @param int $type 采购类型,默认为订单采购,可传参数[1(订单采购); 2(备货采购); 3(样品采购)]
* @return bool * @return bool
* @throws \Meibuyu\Micro\Exceptions\RpcException * @throws \Meibuyu\Micro\Exceptions\RpcException
* @author Zero * @author Zero
*/ */
public function updateProduct($sourceId, array $data, $type = 1); public function updateProduct($sourceId, array $data, $type = 1);
/** /**
* 查询来源id * 查询来源id
* @param array $params // 请勿同时传入 * @param array $params // 请勿同时传入
* [ * [
* "purchase_platform_no" => "采购平台单号", * "purchase_platform_no" => "采购平台单号",
* "logistics_records" => "物流单号", * "logistics_records" => "物流单号",
* ] * ]
* @return array * @return array
* @author Zero * @author Zero
*/ */
public function querySourceIds($params); public function querySourceIds($params);
} }
<?php <?php
/** /**
* Created by PhpStorm. 仓库原料rpc * Created by PhpStorm. 仓库原料rpc
* User: fuyunnan * User: fuyunnan
* Date: 2020/3/16 * Date: 2020/3/16
* Time: 15:07 * Time: 15:07
*/ */
namespace Meibuyu\Micro\Service\Interfaces\Store; namespace Meibuyu\Micro\Service\Interfaces\Store;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Store\StoreMaterialServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Store\StoreMaterialServiceInterface
*/ */
interface StoreMaterialServiceInterface interface StoreMaterialServiceInterface
{ {
/** /**
* description:创建原料入库单 * description:创建原料入库单
* *
* data[master][warehousing_date]:2020-01-08 入库时间 * data[master][warehousing_date]:2020-01-08 入库时间
* data[master][creator_id]:12 创建人id * data[master][creator_id]:12 创建人id
* data[master][warehouse_id]:2 仓库id * data[master][warehouse_id]:2 仓库id
* data[master][type_id]:1 入库单类型 * data[master][type_id]:1 入库单类型
* data[master][source_no]:no_121333 来源单号 (选填) * data[master][source_no]:no_121333 来源单号 (选填)
* data[master][remark]:备注 (选填) * data[master][remark]:备注 (选填)
* data[master][status]:2 状态 (选填 不填默认1) * data[master][status]:2 状态 (选填 不填默认1)
* *
* 产品二维数组 * 产品二维数组
* data[goods][0][material_id]:16 产品id * data[goods][0][material_id]:16 产品id
* data[goods][0][should_cnt]:133 应入数量 * data[goods][0][should_cnt]:133 应入数量
* data[goods][0][real_cnt]:10 实入数量 * data[goods][0][real_cnt]:10 实入数量
* data[goods][1][material_id]:18 * data[goods][1][material_id]:18
* data[goods][1][should_cnt]:10 * data[goods][1][should_cnt]:10
* data[goods][1][real_cnt]:15 * data[goods][1][real_cnt]:15
* *
* author: fuyunnan * author: fuyunnan
* @param array $attributes 需要入库的数组 格式请参考yapi 入库添加 * @param array $attributes 需要入库的数组 格式请参考yapi 入库添加
* @return array * @return array
* @throws * @throws
* Date: 2020/7/6 * Date: 2020/7/6
*/ */
public function createMaterialWarehousing(array $attributes): array; public function createMaterialWarehousing(array $attributes): array;
/** /**
* description:批量创建入库单 * description:批量创建入库单
* author: fuyunnan * author: fuyunnan
* @param * @param
* @return array * @return array
* @throws * @throws
* Date: 2020/10/31 * Date: 2020/10/31
*/ */
public function createBatchMaterialWarehousing($attributes): array; public function createBatchMaterialWarehousing($attributes): array;
/** /**
* description:批量创建出库单 * description:批量创建出库单
* author: fuyunnan * author: fuyunnan
* @param * @param
* @return array * @return array
* @throws * @throws
* Date: 2020/10/31 * Date: 2020/10/31
*/ */
public function createBatchExMaterialWarehouse($attributes): array; public function createBatchExMaterialWarehouse($attributes): array;
/** /**
* description:批量修改入库单 * description:批量修改入库单
* author: fuyunnan * author: fuyunnan
* @param * @param
* @return array * @return array
* @throws * @throws
* Date: 2020/10/31 * Date: 2020/10/31
*/ */
public function updateBatchMaterialWarehousing($attributes): array; public function updateBatchMaterialWarehousing($attributes): array;
/** /**
* description:批量修改出库单 * description:批量修改出库单
* author: fuyunnan * author: fuyunnan
* @param * @param
* @return array * @return array
* @throws * @throws
* Date: 2020/10/31 * Date: 2020/10/31
*/ */
public function updateBatchExMaterialWarehouse($attributes): array; public function updateBatchExMaterialWarehouse($attributes): array;
/** /**
* description:通过原料id数组获取库存列表 给订单系统查询的接口 返回当前原料分组后的库存 * description:通过原料id数组获取库存列表 给订单系统查询的接口 返回当前原料分组后的库存
* author: fuyunnan * author: fuyunnan
* @param array $ids 原料ids 数组 * @param array $ids 原料ids 数组
* @param array $wareIds 仓库数组id * @param array $wareIds 仓库数组id
* @return array * @return array
* @throws * @throws
* Date: 2020/7/27 * Date: 2020/7/27
*/ */
public function getGroupMaterialStock($ids, $wareIds = []): array; public function getGroupMaterialStock($ids, $wareIds = []): array;
/** /**
* description:批量查看入库单信息 * description:批量查看入库单信息
* author: fuyunnan * author: fuyunnan
* @param array $ids 入库单ids数组 * @param array $ids 入库单ids数组
* @param array $relations 关联关系 ['material_warehousing_order_materials'] * @param array $relations 关联关系 ['material_warehousing_order_materials']
* @return array * @return array
* @throws * @throws
* Date: 2020/10/31 * Date: 2020/10/31
*/ */
public function showBatchWarehousing($ids, $relations = []): array; public function showBatchWarehousing($ids, $relations = []): array;
/** /**
* description:批量查看出库单信息 * description:批量查看出库单信息
* author: fuyunnan * author: fuyunnan
* @param array $ids 出库单ids数组 * @param array $ids 出库单ids数组
* @param array $relations 关联关系 ['material_ex_warehouse_order_materials'] * @param array $relations 关联关系 ['material_ex_warehouse_order_materials']
* @return array * @return array
* @throws * @throws
* Date: 2020/10/31 * Date: 2020/10/31
*/ */
public function showBatchExeWarehouse($ids, $relations = []): array; public function showBatchExeWarehouse($ids, $relations = []): array;
/** /**
* description:批量调拨库存方法 * description:批量调拨库存方法
* author: fuyunnan * author: fuyunnan
* @param array $data 表单 * @param array $data 表单
* @return array * @return array
* @throws * @throws
* Date: 2020/11/3 * Date: 2020/11/3
*/ */
public function transferToStock($data): array; public function transferToStock($data): array;
/** /**
* description:整合 先出库 然后 再入库数量 失败回滚 * description:整合 先出库 然后 再入库数量 失败回滚
* author: fuyunnan * author: fuyunnan
* @param array $outData 出库数组 * @param array $outData 出库数组
* @param array $inData 出库数组 * @param array $inData 出库数组
* @return array * @return array
* @throws * @throws
* Date: 2020/11/5 * Date: 2020/11/5
*/ */
public function transferUpdateOutAfterIn($outData, $inData): array; public function transferUpdateOutAfterIn($outData, $inData): array;
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 王源 * User: 王源
* Date: 2020/3/16 * Date: 2020/3/16
* Time: 15:07 * Time: 15:07
*/ */
namespace Meibuyu\Micro\Service\Interfaces; namespace Meibuyu\Micro\Service\Interfaces;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Store\StoreServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\Store\StoreServiceInterface
*/ */
interface StoreServiceInterface interface StoreServiceInterface
{ {
/** /**
* 通过id列表获取仓库名称 * 通过id列表获取仓库名称
* @param array $idList 仓库id的列表, 默认去重 * @param array $idList 仓库id的列表, 默认去重
* @param array $columns 仓库表的字段,默认显示全部 * @param array $columns 仓库表的字段,默认显示全部
* @return array 默认keyBy('id') * @return array 默认keyBy('id')
*/ */
public function getByIdList(array $idList, array $columns = ['*']): array; public function getByIdList(array $idList, array $columns = ['*']): array;
/** /**
* description:通过产品id数组获取库存列表 给订单系统查询的接口 * description:通过产品id数组获取库存列表 给订单系统查询的接口
* author: fuyunnan * author: fuyunnan
* @param array $ids 产品ids 数组 * @param array $ids 产品ids 数组
* @param int $wareId 仓库id * @param int $wareId 仓库id
* @param array $notWareId 仓库id * @param array $notWareId 仓库id
* @return array * @return array
* @throws * @throws
* Date: 2020/7/27 * Date: 2020/7/27
*/ */
public function getListStock($ids, $wareId = 0, $notWareId = []): array; public function getListStock($ids, $wareId = 0, $notWareId = []): array;
/** /**
* description:根据筛选条件获取仓库的库存列表 对库存筛选实现大一统 * description:根据筛选条件获取仓库的库存列表 对库存筛选实现大一统
* 参数格式 不需要可不传入对应的键 * 参数格式 不需要可不传入对应的键
* $args['inTeamIds'] =[]; * $args['inTeamIds'] =[];
$args['notInTeamIds'] = []; $args['notInTeamIds'] = [];
$args['inWhIds'] = []; //仓库id $args['inWhIds'] = []; //仓库id
$args['notInWhIds'] = []; $args['notInWhIds'] = [];
$args['inProductIds'] = []; $args['inProductIds'] = [];
$args['notInProductIds'] = []; $args['notInProductIds'] = [];
$args['where'] = []; $args['where'] = [];
$args['group'] = ['product_id'];//默认['product_id'] $args['group'] = ['product_id'];//默认['product_id']
$args['keyBy'] = 'product_id';//默认排序 $args['keyBy'] = 'product_id';//默认排序
$args['isKeyBy'] = $condition['isKeyBy'] ?? true;//是否加keyBy; $args['isKeyBy'] = $condition['isKeyBy'] ?? true;//是否加keyBy;
$args['isGroupBy'] = $condition['isGroupBy'] ?? true;//是否加分组; $args['isGroupBy'] = $condition['isGroupBy'] ?? true;//是否加分组;
* *
* author: fuyunnan * author: fuyunnan
* @param array $condition 筛选条件 * @param array $condition 筛选条件
* @return array * @return array
* @throws * @throws
* Date: 2020/7/27 * Date: 2020/7/27
*/ */
public function getListStockWhere($condition): array; public function getListStockWhere($condition): array;
/** /**
* description:检查是否有库存,有就返回库存数量(有记录) 给产品系统使用 * description:检查是否有库存,有就返回库存数量(有记录) 给产品系统使用
* author: fuyunnan * author: fuyunnan
* @param array $ids 仓库产品的id数组 * @param array $ids 仓库产品的id数组
* @return array * @return array
* @throws * @throws
* Date: 2020/7/31 * Date: 2020/7/31
*/ */
public function checkStock($ids): array; public function checkStock($ids): array;
/** /**
* description:创建入库单 * description:创建入库单
* author: fuyunnan * author: fuyunnan
* @param array $data 需要入库的数组 格式 入库添加 * @param array $data 需要入库的数组 格式 入库添加
* * * *
* data[master][warehousing_date]:2020-01-08 入库时间 * data[master][warehousing_date]:2020-01-08 入库时间
* data[master][creator_id]:12 创建人id * data[master][creator_id]:12 创建人id
* data[master][warehouse_id]:2 仓库id * data[master][warehouse_id]:2 仓库id
* data[master][type_id]:1 入库单类型 * data[master][type_id]:1 入库单类型
* data[master][source_no]:no_121333 来源单号 (选填) * data[master][source_no]:no_121333 来源单号 (选填)
* data[master][stock_up_status]:1二次质检状态 (选填) * data[master][stock_up_status]:1二次质检状态 (选填)
* data[master][remark]:备注 (选填) * data[master][remark]:备注 (选填)
* data[master][status]:2 状态 (选填 不填默认1) * data[master][status]:2 状态 (选填 不填默认1)
* *
* 产品二维数组 * 产品二维数组
* data[goods][0][product_id]:16 产品id * data[goods][0][product_id]:16 产品id
* data[goods][0][should_cnt]:133 应入数量 * data[goods][0][should_cnt]:133 应入数量
* data[goods][0][real_cnt]:10 实入数量 * data[goods][0][real_cnt]:10 实入数量
* data[goods][1][product_id]:18 * data[goods][1][product_id]:18
* data[goods][1][should_cnt]:10 * data[goods][1][should_cnt]:10
* data[goods][1][real_cnt]:15 * data[goods][1][real_cnt]:15
* *
* 或者参考yapi http://api.huaperfect.com/project/38/interface/api/1617 * 或者参考yapi http://api.huaperfect.com/project/38/interface/api/1617
* *
* @return array * @return array
* @throws * @throws
* Date: 2020/7/6 * Date: 2020/7/6
*/ */
public function createWarehousing(array $data): array; public function createWarehousing(array $data): array;
/** /**
* description:批量创建出库单 * description:批量创建出库单
* author: fuyunnan * author: fuyunnan
* [ * [
* 'main' => [ * 'main' => [
*     'creator_id' => 1, *     'creator_id' => 1,
*     'warehouse_id' => 1, *     'warehouse_id' => 1,
*     'type' => 5, *     'type' => 5,
* ], * ],
* 'products' => [ * 'products' => [
* [ * [
*     'source_no' => 1, *     'source_no' => 1,
*     'product_id' => 1, *     'product_id' => 1,
*     'real_cnt' => 1 *     'real_cnt' => 1
* ], * ],
* [ * [
*     'source_no' => 1, *     'source_no' => 1,
*     'product_id' => 1, *     'product_id' => 1,
*     'real_cnt' => 1 *     'real_cnt' => 1
* ] * ]
* ] * ]
* ] * ]
* *
* @param array $attributes 提交的数组 或参考yapi http://api.huaperfect.com/project/38/interface/api/6968 * @param array $attributes 提交的数组 或参考yapi http://api.huaperfect.com/project/38/interface/api/6968
* @return bool * @return bool
* @throws * @throws
* Date: 2020/8/8 * Date: 2020/8/8
*/ */
public function createBatchWarehousing(array $attributes): bool; public function createBatchWarehousing(array $attributes): bool;
/** /**
* description:根据入库单状态,判断是否生成出库单 * description:根据入库单状态,判断是否生成出库单
* author: fuyunnan * author: fuyunnan
* @param array $data 需要入库或者出库的数据 * @param array $data 需要入库或者出库的数据
* @return bool * @return bool
* @throws * @throws
* Date: 2021/5/25 * Date: 2021/5/25
*/ */
public function createInOrOutOrder(array $data): bool; public function createInOrOutOrder(array $data): bool;
/** /**
* description:创建入库单 支持自定义 入库单状态和仓位 * description:创建入库单 支持自定义 入库单状态和仓位
* author: fuyunnan * author: fuyunnan
* @param array $attributes 需要入库的数组 格式请参考yapi 入库添加 * @param array $attributes 需要入库的数组 格式请参考yapi 入库添加
* @return bool * @return bool
* @throws * @throws
* Date: 2020/7/6 * Date: 2020/7/6
*/ */
public function createWarehousingStatus(array $attributes): bool; public function createWarehousingStatus(array $attributes): bool;
/** /**
* description:批量创建出库单,多个仓库 直接出虚拟仓 * description:批量创建出库单,多个仓库 直接出虚拟仓
* author: fuyunnan * author: fuyunnan
* @param array $attributes 提交的数组 参考yapi http://api.huaperfect.com/project/38/interface/api/6968 * @param array $attributes 提交的数组 参考yapi http://api.huaperfect.com/project/38/interface/api/6968
* @return bool * @return bool
* @throws * @throws
* Date: 2020/8/8 * Date: 2020/8/8
*/ */
public function createBatchWarehousingStatus(array $attributes): bool; public function createBatchWarehousingStatus(array $attributes): bool;
/** /**
* description:批量创建出库单,出库单直接出库 * description:批量创建出库单,出库单直接出库
* author: fuyunnan * author: fuyunnan
* @param array $attributes 提交的数组 参考yapi http://api.huaperfect.com/project/38/interface/api/6968 * @param array $attributes 提交的数组 参考yapi http://api.huaperfect.com/project/38/interface/api/6968
* @return bool * @return bool
* @throws * @throws
* Date: 2020/8/8 * Date: 2020/8/8
*/ */
public function createBatchExComplete(array $attributes): bool; public function createBatchExComplete(array $attributes): bool;
/** /**
* description:批量创建入库单 * description:批量创建入库单
* author: fuyunnan * author: fuyunnan
* @param array $attributes 需要入库的数组 格式请参考yapi 入库添加 * @param array $attributes 需要入库的数组 格式请参考yapi 入库添加
* @return bool * @return bool
* @throws * @throws
* Date: 2020/7/6 * Date: 2020/7/6
*/ */
public function createBatchInOrder(array $attributes): bool; public function createBatchInOrder(array $attributes): bool;
/** /**
* description:批量创建入库单,能自定义入库单状态 * description:批量创建入库单,能自定义入库单状态
* author: fuyunnan * author: fuyunnan
* @param array $attributes 需要入库的数组 格式请参考yapi 入库添加 * @param array $attributes 需要入库的数组 格式请参考yapi 入库添加
* @return bool * @return bool
* @throws * @throws
* Date: 2020/7/6 * Date: 2020/7/6
*/ */
public function createBatchInOrderStatus(array $attributes): bool; public function createBatchInOrderStatus(array $attributes): bool;
/** /**
* description:生产单结束获取统计单号值 * description:生产单结束获取统计单号值
* author: fuyunnan * author: fuyunnan
* @param string $sourceNo 生产单号 * @param string $sourceNo 生产单号
* @return array * @return array
* @throws * @throws
* Date: 2020/7/10 * Date: 2020/7/10
*/ */
public function CntSourceNoOrder($sourceNo): array; public function CntSourceNoOrder($sourceNo): array;
/** /**
* description:通过来源单号获取产品列表 * description:通过来源单号获取产品列表
* author: fuyunnan * author: fuyunnan
* @param string $sourceNo 生产单号 * @param string $sourceNo 生产单号
* @return array * @return array
* @throws * @throws
* Date: 2020/7/10 * Date: 2020/7/10
*/ */
public function listSourceNoProduct($sourceNo): array; public function listSourceNoProduct($sourceNo): array;
/** /**
* description:根据来源单号,获取分组后的入库单 * description:根据来源单号,获取分组后的入库单
* author: fuyunnan * author: fuyunnan
* @param array $sourceNoList 单号列表 * @param array $sourceNoList 单号列表
* @param array $where 刷选列表 * @param array $where 刷选列表
* @return array * @return array
* @throws * @throws
* Date: 2020/7/11 * Date: 2020/7/11
*/ */
public function listGroupOrder($sourceNoList, $where = []): array; public function listGroupOrder($sourceNoList, $where = []): array;
/** /**
* description:根据条件查询入库单信息 * description:根据条件查询入库单信息
* author: fuyunnan * author: fuyunnan
* 参数注意 必须这样传!!! * 参数注意 必须这样传!!!
* $condition = [ * $condition = [
* 'warehousing_order_ids' =>$ids 可选 入库单ids数组 * 'warehousing_order_ids' =>$ids 可选 入库单ids数组
* ] * ]
* @param array $condition 条件 * @param array $condition 条件
* @return array * @return array
* @throws * @throws
* Date: 2020/7/11 * Date: 2020/7/11
*/ */
public function getListInOrder($condition): array; public function getListInOrder($condition): array;
/** /**
* description:通过入库单id数组获取产品列表 * description:通过入库单id数组获取产品列表
* author: fuyunnan * author: fuyunnan
* @param array $ids 入库单ids 数组 * @param array $ids 入库单ids 数组
* @return array * @return array
* @throws * @throws
* Date: 2020/7/10 * Date: 2020/7/10
*/ */
public function listIdsProduct($ids): array; public function listIdsProduct($ids): array;
/** /**
* description:修改二次质检状态 * description:修改二次质检状态
* author: fuyunnan * author: fuyunnan
* @param int $orderId 入库单id * @param int $orderId 入库单id
* @param array $update 修改数组 * @param array $update 修改数组
* @return int * @return int
* @throws * @throws
* Date: 2020/7/14 * Date: 2020/7/14
*/ */
public function updateQualityStatus($orderId, $update): int; public function updateQualityStatus($orderId, $update): int;
/** /**
* description:修改二次质检状态 * description:修改二次质检状态
* author: fuyunnan * author: fuyunnan
* @param array $orderIds 入库单id数组 * @param array $orderIds 入库单id数组
* @param array $update 修改数组 * @param array $update 修改数组
* @return int * @return int
* @throws * @throws
* Date: 2020/7/14 * Date: 2020/7/14
*/ */
public function updateListQualityStatus($orderIds, $update): int; public function updateListQualityStatus($orderIds, $update): int;
/** /**
* description:出库单 恢复库存 出库单定为已取消 * description:出库单 恢复库存 出库单定为已取消
* author: fuyunnan * author: fuyunnan
* @param array $sourceNo 来源单号数组 * @param array $sourceNo 来源单号数组
* @return int * @return int
* @throws * @throws
* Date: 2020/9/7 * Date: 2020/9/7
*/ */
public function restoreStock($sourceNo): int; public function restoreStock($sourceNo): int;
/** /**
* description:通过出库来源单号获取-对应的信息 * description:通过出库来源单号获取-对应的信息
* author: fuyunnan * author: fuyunnan
* @param array $sources 来源单号数组 * @param array $sources 来源单号数组
* @param array $status 出库单状态 * @param array $status 出库单状态
* @param array $where 查询条件数组 * @param array $where 查询条件数组
* @return array * @return array
* @throws * @throws
* Date: 2020/11/5 * Date: 2020/11/5
*/ */
public function getByExSourceList($sources, $status = [], $where = []): array; public function getByExSourceList($sources, $status = [], $where = []): array;
/** /**
* description:自动返回匹配的符合当前sku * description:自动返回匹配的符合当前sku
* author: fuyunnan * author: fuyunnan
* @param array $data sku数组 * @param array $data sku数组
* @return array * @return array
* @throws * @throws
* Date: 2020/11/25 * Date: 2020/11/25
*/ */
public function autoSkuStock($data): array; public function autoSkuStock($data): array;
/** /**
* description:订单通知取消更改字段 不在生成出库单 * description:订单通知取消更改字段 不在生成出库单
* author: fuyunnan * author: fuyunnan
* @param string $sourceNos 来源单号 * @param string $sourceNos 来源单号
* @param array $field 修改字段 * @param array $field 修改字段
* @return int * @return int
* @throws * @throws
* Date: 2020/12/14 * Date: 2020/12/14
*/ */
public function cancelOrderDeliver($sourceNos, $field): int; public function cancelOrderDeliver($sourceNos, $field): int;
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: zero * User: zero
* Date: 2020/5/26 * Date: 2020/5/26
* Time: 15:17 * Time: 15:17
*/ */
namespace Meibuyu\Micro\Service\Interfaces\User; namespace Meibuyu\Micro\Service\Interfaces\User;
/** /**
* @deprecated 此接口废弃,在之后的版本会被删除 * @deprecated 此接口废弃,在之后的版本会被删除
* 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\User\AccessServiceInterface * 请引入meibuyu/rpc组件,使用Meibuyu\Rpc\Service\Interfaces\User\AccessServiceInterface
*/ */
interface AccessServiceInterface interface AccessServiceInterface
{ {
/** /**
* 判断用户是否在业务部门(包括子部门) * 判断用户是否在业务部门(包括子部门)
* @param $userId * @param $userId
* @return mixed * @return mixed
*/ */
public function isBusinessDepartment($userId); public function isBusinessDepartment($userId);
/** /**
* 获取用户领导的部门id数组 * 获取用户领导的部门id数组
* @param $userId * @param $userId
* @return array * @return array
*/ */
public function leadDeptIds($userId); public function leadDeptIds($userId);
/** /**
* 获取用户领导的团队id数组 * 获取用户领导的团队id数组
* @param $userId * @param $userId
* @return array * @return array
*/ */
public function leadTeamIds($userId); public function leadTeamIds($userId);
/** /**
* 获取鉴权的团队 * 获取鉴权的团队
* @param $userId * @param $userId
* @param bool $tree 是否返回树状结构 * @param bool $tree 是否返回树状结构
* @param bool $noBusiness * @param bool $noBusiness
* @return array 已进行keyBy('id')处理,返回树状结构时,keyBy无效 * @return array 已进行keyBy('id')处理,返回树状结构时,keyBy无效
*/ */
public function getTeams($userId, $tree = false, $noBusiness = true); public function getTeams($userId, $tree = false, $noBusiness = true);
/** /**
* 获取鉴权的团队id数组 * 获取鉴权的团队id数组
* @param $userId * @param $userId
* @param bool $checkBusiness 是否验证业务部门(验证时,不是业务部门返回空团队;不验证时,不是业务部门返回all),默认不验证 * @param bool $checkBusiness 是否验证业务部门(验证时,不是业务部门返回空团队;不验证时,不是业务部门返回all),默认不验证
* @return array|string 如果是全部团队返回'all'字符串 * @return array|string 如果是全部团队返回'all'字符串
* @author Zero * @author Zero
*/ */
public function getTeamIds($userId, $checkBusiness = false); public function getTeamIds($userId, $checkBusiness = false);
/** /**
* 获取鉴权的团队带用户 * 获取鉴权的团队带用户
* @param $userId * @param $userId
* @param bool $tree 是否返回树状结构 * @param bool $tree 是否返回树状结构
* @param bool $noBusiness * @param bool $noBusiness
* @return array 已进行keyBy('id')处理,返回树状结构时,keyBy无效 * @return array 已进行keyBy('id')处理,返回树状结构时,keyBy无效
*/ */
public function getTeamsWithUsers($userId, $tree = false, $noBusiness = true); public function getTeamsWithUsers($userId, $tree = false, $noBusiness = true);
/** /**
* 获取鉴权的部门 * 获取鉴权的部门
* @param $userId * @param $userId
* @param bool $tree 是否返回树状结构 * @param bool $tree 是否返回树状结构
* @param bool $withUser 是否带用户数据 * @param bool $withUser 是否带用户数据
* @return array 已进行keyBy('id')处理,返回树状结构时,keyBy无效 * @return array 已进行keyBy('id')处理,返回树状结构时,keyBy无效
*/ */
public function getDepartments($userId, $tree = false, $withUser = false); public function getDepartments($userId, $tree = false, $withUser = false);
/** /**
* 获取鉴权的岗位 * 获取鉴权的岗位
* @param $userId * @param $userId
* @param bool $tree 是否返回树状结构 * @param bool $tree 是否返回树状结构
* @param bool $withUser * @param bool $withUser
* @return array 已进行keyBy('id')处理,返回树状结构时,keyBy无效 * @return array 已进行keyBy('id')处理,返回树状结构时,keyBy无效
*/ */
public function getPositions($userId, $tree = false, $withUser = false); public function getPositions($userId, $tree = false, $withUser = false);
/** /**
* 获取鉴权的用户id列表 * 获取鉴权的用户id列表
* @param int $userId 当前用户id * @param int $userId 当前用户id
* @return array|string 如果是全部用户返回'all'字符串 * @return array|string 如果是全部用户返回'all'字符串
*/ */
public function getUserIds($userId); public function getUserIds($userId);
/** /**
* 获取鉴权的用户id列表 * 获取鉴权的用户id列表
* 不验证业务部门 * 不验证业务部门
* @param int $userId 当前用户id * @param int $userId 当前用户id
* @return array|string 如果是全部用户返回'all'字符串 * @return array|string 如果是全部用户返回'all'字符串
* @author zero * @author zero
*/ */
public function getUserIdsWithoutBusiness($userId); public function getUserIdsWithoutBusiness($userId);
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: zero * User: zero
* Date: 2020/5/26 * Date: 2020/5/26
* Time: 15:17 * Time: 15:17
*/ */
namespace Meibuyu\Micro\Service\Interfaces\User; namespace Meibuyu\Micro\Service\Interfaces\User;
interface AuthenticationServiceInterface interface AuthenticationServiceInterface
{ {
/** /**
* 获取对应用户能够看到的菜单 * 获取对应用户能够看到的菜单
* @param string $applicationName * @param string $applicationName
* @param integer $userId * @param integer $userId
* @return array * @return array
*/ */
public function getMenus($applicationName, $userId): array; public function getMenus($applicationName, $userId): array;
/** /**
* 获取对应用户的菜单权限 * 获取对应用户的菜单权限
* @param string $applicationName 应用名称 * @param string $applicationName 应用名称
* @param integer $userId 用户 ID * @param integer $userId 用户 ID
* @return array * @return array
*/ */
public function getButtons($applicationName, $userId):array; public function getButtons($applicationName, $userId):array;
/** /**
* 获取对应路由的接口权限结果 * 获取对应路由的接口权限结果
* @param $route string 路由名字 * @param $route string 路由名字
* @param $applicationName string 应用名字 * @param $applicationName string 应用名字
* @param $method string 请求方法 * @param $method string 请求方法
* @param $userId integer 用户 ID * @param $userId integer 用户 ID
* @return bool * @return bool
*/ */
public function authByRouter($applicationName, $route, $method, $userId): bool; public function authByRouter($applicationName, $route, $method, $userId): bool;
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: 王源 * User: 王源
* Date: 2020/1/9 * Date: 2020/1/9
* Time: 15:07 * Time: 15:07
*/ */
namespace Meibuyu\Micro\Service\Interfaces; namespace Meibuyu\Micro\Service\Interfaces;
interface UserServiceInterface interface UserServiceInterface
{ {
/** /**
* 通过用户名称模糊获取用户 * 通过用户名称模糊获取用户
* @param string $name * @param string $name
* @param array $columns * @param array $columns
* @return array * @return array
*/ */
public function getByName(string $name, array $columns = ['id', 'name']): array; public function getByName(string $name, array $columns = ['id', 'name']): array;
/** /**
* 获取单个数据 * 获取单个数据
* @param int $id * @param int $id
* @param array $columns * @param array $columns
* @param array $relations 可传入['teams', 'departments', 'position', 'assessment_plan'],分别是团队,部门,岗位和考核方案 * @param array $relations 可传入['teams', 'departments', 'position', 'assessment_plan'],分别是团队,部门,岗位和考核方案
* @return mixed * @return mixed
*/ */
public function get(int $id, array $columns = ['*'], array $relations = []); public function get(int $id, array $columns = ['*'], array $relations = []);
/** /**
* 获取全部数据 * 获取全部数据
* @param array $columns 默认['id', 'name'] * @param array $columns 默认['id', 'name']
* @param array $relations 可传入['teams', 'departments', 'position', 'assessment_plan'],分别是团队,部门,岗位和考核方案 * @param array $relations 可传入['teams', 'departments', 'position', 'assessment_plan'],分别是团队,部门,岗位和考核方案
* @return array * @return array
*/ */
public function all(array $columns = ['id', 'name'], array $relations = []): array; public function all(array $columns = ['id', 'name'], array $relations = []): array;
/** /**
* 通过id列表获取用户数组 * 通过id列表获取用户数组
* @param array $idList 默认去重 * @param array $idList 默认去重
* @param array $columns * @param array $columns
* @param array $relations 可传入['teams', 'departments', 'position', 'assessment_plan'],分别是团队,部门,岗位和考核方案 * @param array $relations 可传入['teams', 'departments', 'position', 'assessment_plan'],分别是团队,部门,岗位和考核方案
* @return mixed 默认keyBY('id') * @return mixed 默认keyBY('id')
*/ */
public function getByIdList($idList, $columns = ['*'], $relations = []); public function getByIdList($idList, $columns = ['*'], $relations = []);
/** /**
* 通过部门id列表获取用户数组(包括子部门用户) * 通过部门id列表获取用户数组(包括子部门用户)
* @param array $deptIds 默认去重 * @param array $deptIds 默认去重
* @param array $columns 用户字段,默认['id', 'name'] * @param array $columns 用户字段,默认['id', 'name']
* @return array * @return array
*/ */
public function getListByDeptIds(array $deptIds, $columns = []); public function getListByDeptIds(array $deptIds, $columns = []);
/** /**
* 通过团队id数组获取用户数组(包括子团队用户) * 通过团队id数组获取用户数组(包括子团队用户)
* @param array $teamIds 默认去重 * @param array $teamIds 默认去重
* @param array $columns 用户字段,默认['id', 'name'] * @param array $columns 用户字段,默认['id', 'name']
* @return array * @return array
*/ */
public function getListByTeamIds(array $teamIds, $columns = []); public function getListByTeamIds(array $teamIds, $columns = []);
/** /**
* 判断是否是超级管理员 * 判断是否是超级管理员
* @param int $userId * @param int $userId
* @return bool * @return bool
*/ */
public function isSuperAdmin(int $userId): bool; public function isSuperAdmin(int $userId): bool;
/** /**
* 鉴权 * 鉴权
* @param int $userId * @param int $userId
* @param string $perm * @param string $perm
* @return bool * @return bool
*/ */
public function checkPerm(int $userId, string $perm): bool; public function checkPerm(int $userId, string $perm): bool;
/** /**
* 获取当前数据权限的配置 * 获取当前数据权限的配置
* @param string $dataPerm * @param string $dataPerm
* @return array * @return array
* @example store_warehouse_index(store_模块的名称,warehouse_ 控制器 index 方法) * @example store_warehouse_index(store_模块的名称,warehouse_ 控制器 index 方法)
*/ */
public function checkDataPerm(string $dataPerm): array; public function checkDataPerm(string $dataPerm): array;
/** /**
* 获取用户拥有某个应用的所有权限 * 获取用户拥有某个应用的所有权限
* @param int $userId * @param int $userId
* @param mixed $appNames 应用名,多个传数组 * @param mixed $appNames 应用名,多个传数组
* @return array * @return array
*/ */
public function getPerms(int $userId, $appNames = null): array; public function getPerms(int $userId, $appNames = null): array;
/** /**
* 获取带领导字符串数组的列表 * 获取带领导字符串数组的列表
* [ * [
* ['id' => -1, 'name' => '总经理'], * ['id' => -1, 'name' => '总经理'],
* ['id' => -2, 'name' => '直属领导'], * ['id' => -2, 'name' => '直属领导'],
* ['id' => -3, 'name' => '部门领导'], * ['id' => -3, 'name' => '部门领导'],
* [...] * [...]
* ] * ]
* @return array * @return array
*/ */
public function allWithLeader(): array; public function allWithLeader(): array;
/** /**
* 获取带有领导真实信息的用户列表 * 获取带有领导真实信息的用户列表
* @param int $userId 默认去重 * @param int $userId 默认去重
* @param array $idList 可包含[-1,-2,-3] * @param array $idList 可包含[-1,-2,-3]
* @param array $columns * @param array $columns
* @return array 默认keyBY('id') * @return array 默认keyBY('id')
*/ */
public function getListWithLeader(int $userId, array $idList = [], array $columns = ['id', 'name']): array; public function getListWithLeader(int $userId, array $idList = [], array $columns = ['id', 'name']): array;
/** /**
* 更新用户考核方案 * 更新用户考核方案
* @param $userId * @param $userId
* @param array $attributes * @param array $attributes
* 'review_users' => '1,2,3' // 点评人 * 'review_users' => '1,2,3' // 点评人
* 'cc_person' => '1,2,3' // 抄送人 * 'cc_person' => '1,2,3' // 抄送人
* @return int * @return int
*/ */
public function updateAssessmentPlan($userId, array $attributes); public function updateAssessmentPlan($userId, array $attributes);
/** /**
* 获取用户直属领导 * 获取用户直属领导
* @param int $userId 用户id * @param int $userId 用户id
* @return array * @return array
*/ */
public function getDirectLeader($userId); public function getDirectLeader($userId);
/** /**
* 获取多个用户的直属领导 * 获取多个用户的直属领导
* @param array $userIds 用户id数组,默认去重 * @param array $userIds 用户id数组,默认去重
* @return array 直属领导数组,key值为用户id * @return array 直属领导数组,key值为用户id
*/ */
public function getDirectLeadersByIds($userIds); public function getDirectLeadersByIds($userIds);
/** /**
* 判断用户是否属于某个部门 * 判断用户是否属于某个部门
* @param mixed $userId 用户id * @param mixed $userId 用户id
* @param mixed $deptId 部门id,判断多个部门传数组 * @param mixed $deptId 部门id,判断多个部门传数组
* @param bool $withChildren 是否包含子部门,默认false * @param bool $withChildren 是否包含子部门,默认false
* @return bool * @return bool
* @author Zero * @author Zero
*/ */
public function belongToDepartments($userId, $deptId, $withChildren = false): bool; public function belongToDepartments($userId, $deptId, $withChildren = false): bool;
/** /**
* 获取用户所有角色数据 * 获取用户所有角色数据
* @param $userId * @param $userId
* @return array * @return array
* @author Zero * @author Zero
*/ */
public function getRoles($userId): array; public function getRoles($userId): array;
} }
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: Zero * User: Zero
* Date: 2020/8/18 * Date: 2020/8/18
* Time: 8:13 * Time: 8:13
*/ */
namespace Meibuyu\Micro\Shopify; namespace Meibuyu\Micro\Shopify;
use Exception; use Exception;
use Meibuyu\Micro\Shopify\lib\AbstractShopify; use Meibuyu\Micro\Shopify\lib\AbstractShopify;
use Meibuyu\Micro\Shopify\lib\Collect; use Meibuyu\Micro\Shopify\lib\Collect;
use Meibuyu\Micro\Shopify\lib\Collection; use Meibuyu\Micro\Shopify\lib\Collection;
use Meibuyu\Micro\Shopify\lib\CustomCollection; use Meibuyu\Micro\Shopify\lib\CustomCollection;
use Meibuyu\Micro\Shopify\lib\Event; use Meibuyu\Micro\Shopify\lib\Event;
use Meibuyu\Micro\Shopify\lib\Fulfillment; use Meibuyu\Micro\Shopify\lib\Fulfillment;
use Meibuyu\Micro\Shopify\lib\FulfillmentOrder; use Meibuyu\Micro\Shopify\lib\FulfillmentOrder;
use Meibuyu\Micro\Shopify\lib\FulfillmentService; use Meibuyu\Micro\Shopify\lib\FulfillmentService;
use Meibuyu\Micro\Shopify\lib\GraphQL; use Meibuyu\Micro\Shopify\lib\GraphQL;
use Meibuyu\Micro\Shopify\lib\InventoryItem; use Meibuyu\Micro\Shopify\lib\InventoryItem;
use Meibuyu\Micro\Shopify\lib\InventoryLevel; use Meibuyu\Micro\Shopify\lib\InventoryLevel;
use Meibuyu\Micro\Shopify\lib\Location; use Meibuyu\Micro\Shopify\lib\Location;
use Meibuyu\Micro\Shopify\lib\Metafield; use Meibuyu\Micro\Shopify\lib\Metafield;
use Meibuyu\Micro\Shopify\lib\Order; use Meibuyu\Micro\Shopify\lib\Order;
use Meibuyu\Micro\Shopify\lib\Product; use Meibuyu\Micro\Shopify\lib\Product;
use Meibuyu\Micro\Shopify\lib\ProductVariant; use Meibuyu\Micro\Shopify\lib\ProductVariant;
use Meibuyu\Micro\Shopify\lib\SmartCollection; use Meibuyu\Micro\Shopify\lib\SmartCollection;
use Meibuyu\Micro\Shopify\lib\Webhook; use Meibuyu\Micro\Shopify\lib\Webhook;
/** /**
* Class ShopifyApp * Class ShopifyApp
* @package Meibuyu\Shopify * @package Meibuyu\Shopify
* *
* @property-read Webhook $Webhook * @property-read Webhook $Webhook
* @property-read Collect $Collect * @property-read Collect $Collect
* @property-read Collection $Collection * @property-read Collection $Collection
* @property-read CustomCollection $CustomCollection * @property-read CustomCollection $CustomCollection
* @property-read SmartCollection $SmartCollection * @property-read SmartCollection $SmartCollection
* @property-read Metafield $Metafield * @property-read Metafield $Metafield
* @property-read Product $Product * @property-read Product $Product
* @property-read ProductVariant $ProductVariant * @property-read ProductVariant $ProductVariant
* @property-read InventoryItem $InventoryItem * @property-read InventoryItem $InventoryItem
* @property-read InventoryLevel $InventoryLevel * @property-read InventoryLevel $InventoryLevel
* @property-read Location $Location * @property-read Location $Location
* @property-read Order $Order * @property-read Order $Order
* @property-read Event $Event * @property-read Event $Event
* @property-read Fulfillment $Fulfillment * @property-read Fulfillment $Fulfillment
* @property-read FulfillmentService $FulfillmentService * @property-read FulfillmentService $FulfillmentService
* @property-read GraphQL $GraphQL * @property-read GraphQL $GraphQL
* *
* @method Webhook Webhook(integer $id = null) * @method Webhook Webhook(integer $id = null)
* @method Collection Collection(integer $id = null) * @method Collection Collection(integer $id = null)
* @method CustomCollection CustomCollection(integer $id = null) * @method CustomCollection CustomCollection(integer $id = null)
* @method SmartCollection SmartCollection(integer $id = null) * @method SmartCollection SmartCollection(integer $id = null)
* @method Metafield Metafield(integer $id = null) * @method Metafield Metafield(integer $id = null)
* @method Product Product(integer $id = null) * @method Product Product(integer $id = null)
* @method ProductVariant ProductVariant(integer $id = null) * @method ProductVariant ProductVariant(integer $id = null)
* @method InventoryItem InventoryItem(integer $id = null) * @method InventoryItem InventoryItem(integer $id = null)
* @method InventoryLevel InventoryLevel(integer $id = null) * @method InventoryLevel InventoryLevel(integer $id = null)
* @method Location Location(integer $id = null) * @method Location Location(integer $id = null)
* @method Order Order(integer $id = null) * @method Order Order(integer $id = null)
* @method Event Event(integer $id = null) * @method Event Event(integer $id = null)
* @method Fulfillment Fulfillment(integer $id = null) * @method Fulfillment Fulfillment(integer $id = null)
* @method FulfillmentOrder FulfillmentOrder() * @method FulfillmentOrder FulfillmentOrder()
* @method FulfillmentService FulfillmentService(integer $id = null) * @method FulfillmentService FulfillmentService(integer $id = null)
* @method GraphQL GraphQL() * @method GraphQL GraphQL()
* *
*/ */
class ShopifyApp class ShopifyApp
{ {
protected $resources = [ protected $resources = [
'Webhook', 'Webhook',
'Collect', 'Collect',
'Collection', 'Collection',
'CustomCollection', 'CustomCollection',
'SmartCollection', 'SmartCollection',
'Metafield', 'Metafield',
'Product', 'Product',
'ProductVariant', 'ProductVariant',
'InventoryItem', 'InventoryItem',
'InventoryLevel', 'InventoryLevel',
'Location', 'Location',
'Order', 'Order',
'Event', 'Event',
'Fulfillment', 'Fulfillment',
'FulfillmentOrder', 'FulfillmentOrder',
'FulfillmentService', 'FulfillmentService',
'GraphQL', 'GraphQL',
]; ];
protected $childResources = array( protected $childResources = array(
'Fulfillment' => 'Order', 'Fulfillment' => 'Order',
'FulfillmentEvent' => 'Fulfillment', 'FulfillmentEvent' => 'Fulfillment',
'FulfillmentOrder' => 'Order', 'FulfillmentOrder' => 'Order',
'OrderRisk' => 'Order', 'OrderRisk' => 'Order',
'ProductImage' => 'Product', 'ProductImage' => 'Product',
'ProductVariant' => 'Product', 'ProductVariant' => 'Product',
'DiscountCode' => 'PriceRule', 'DiscountCode' => 'PriceRule',
'Refund' => 'Order', 'Refund' => 'Order',
'Transaction' => 'Order', 'Transaction' => 'Order',
); );
public $config = []; public $config = [];
public $defaultApiVersion = '2021-07'; public $defaultApiVersion = '2021-07';
/** /**
* ShopifyApp constructor. * ShopifyApp constructor.
* @param array $config * @param array $config
*/ */
public function __construct($config) public function __construct($config)
{ {
$this->config = [ $this->config = [
'api_version' => $this->defaultApiVersion 'api_version' => $this->defaultApiVersion
]; ];
foreach ($config as $key => $value) { foreach ($config as $key => $value) {
$this->config[$key] = $value; $this->config[$key] = $value;
} }
if (isset($config['shop_url'])) { if (isset($config['shop_url'])) {
$this->setApiUrl(); $this->setApiUrl();
} }
} }
/** /**
* 返回AbstractShopify实例 * 返回AbstractShopify实例
* @param string $className 实现的类名 * @param string $className 实现的类名
* @return AbstractShopify * @return AbstractShopify
* @throws Exception * @throws Exception
*/ */
public function __get($className) public function __get($className)
{ {
return $this->$className(); return $this->$className();
} }
/** /**
* 返回AbstractShopify实例 * 返回AbstractShopify实例
* @param string $className 实现的类名 * @param string $className 实现的类名
* @param $arguments * @param $arguments
* @return AbstractShopify * @return AbstractShopify
* @throws Exception * @throws Exception
*/ */
public function __call($className, $arguments) public function __call($className, $arguments)
{ {
if (!in_array($className, $this->resources)) { if (!in_array($className, $this->resources)) {
if (isset($this->childResources[$className])) { if (isset($this->childResources[$className])) {
$message = "$className 是属于 {$this->childResources[$className]} 的子集, 无法直接访问"; $message = "$className 是属于 {$this->childResources[$className]} 的子集, 无法直接访问";
} else { } else {
$message = "未知类 $className"; $message = "未知类 $className";
} }
throw new Exception($message); throw new Exception($message);
} }
$resourceID = !empty($arguments) ? $arguments[0] : null; $resourceID = !empty($arguments) ? $arguments[0] : null;
$resourceClassName = __NAMESPACE__ . "\\lib\\$className"; $resourceClassName = __NAMESPACE__ . "\\lib\\$className";
return new $resourceClassName($this->config, $resourceID); return new $resourceClassName($this->config, $resourceID);
} }
public function setApiUrl() public function setApiUrl()
{ {
$shopUrl = $this->config['shop_url']; $shopUrl = $this->config['shop_url'];
$shopUrl = preg_replace('#^https?://|/$#', '', $shopUrl); $shopUrl = preg_replace('#^https?://|/$#', '', $shopUrl);
$apiVersion = $this->config['api_version']; $apiVersion = $this->config['api_version'];
$this->config['api_url'] = "https://$shopUrl/admin/api/$apiVersion/"; $this->config['api_url'] = "https://$shopUrl/admin/api/$apiVersion/";
} }
} }
File mode changed from 100644 to 100755
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: Zero * User: Zero
* Date: 2020/8/18 * Date: 2020/8/18
* Time: 8:18 * Time: 8:18
*/ */
namespace Meibuyu\Micro\Shopify\lib; namespace Meibuyu\Micro\Shopify\lib;
use Exception; use Exception;
use Meibuyu\Micro\Shopify\tools\CurlHttpRequestJson; use Meibuyu\Micro\Shopify\tools\CurlHttpRequestJson;
use Meibuyu\Micro\Shopify\tools\HttpRequestJson; use Meibuyu\Micro\Shopify\tools\HttpRequestJson;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
abstract class AbstractShopify abstract class AbstractShopify
{ {
/** /**
* 资源id * 资源id
* @var int * @var int
*/ */
public $id = null; public $id = null;
protected $httpHeaders = []; protected $httpHeaders = [];
protected $resourceUrl; protected $resourceUrl;
protected $resourceKey; protected $resourceKey;
protected $pluralizeKey; protected $pluralizeKey;
/** /**
* 无count方法 * 无count方法
* @var boolean * @var boolean
*/ */
public $countEnabled = true; public $countEnabled = true;
// 子集资源 // 子集资源
protected $childResource = []; protected $childResource = [];
// 自定义请求方法 // 自定义请求方法
protected $customGetActions = []; protected $customGetActions = [];
protected $customPostActions = []; protected $customPostActions = [];
protected $customPutActions = []; protected $customPutActions = [];
protected $customDeleteActions = []; protected $customDeleteActions = [];
private $config; private $config;
/** /**
* @var HttpRequestJson|CurlHttpRequestJson * @var HttpRequestJson|CurlHttpRequestJson
*/ */
private $httpRequestJson; private $httpRequestJson;
/** /**
* AbstractShopify constructor. * AbstractShopify constructor.
* @param $config * @param $config
* @param null $id * @param null $id
* @param string $parentResourceUrl * @param string $parentResourceUrl
* @throws Exception * @throws Exception
*/ */
public function __construct($config, $id = null, $parentResourceUrl = null) public function __construct($config, $id = null, $parentResourceUrl = null)
{ {
$this->config = $config; $this->config = $config;
$this->id = $id; $this->id = $id;
$this->pluralizeKey = $this->pluralizeKey ?: $this->resourceKey . 's'; $this->pluralizeKey = $this->pluralizeKey ?: $this->resourceKey . 's';
$this->resourceUrl = ($parentResourceUrl ? "$parentResourceUrl/" : $config['api_url']) . $this->pluralizeKey . ($this->id ? "/{$this->id}" : ''); $this->resourceUrl = ($parentResourceUrl ? "$parentResourceUrl/" : $config['api_url']) . $this->pluralizeKey . ($this->id ? "/{$this->id}" : '');
$this->httpRequestJson = make(CurlHttpRequestJson::class); $this->httpRequestJson = make(CurlHttpRequestJson::class);
if (isset($config['is_private_app']) && $config['is_private_app'] == false) { if (isset($config['is_private_app']) && $config['is_private_app'] == false) {
// 如果不是私人应用,则使用访问令牌 // 如果不是私人应用,则使用访问令牌
if (isset($config['access_token'])) { if (isset($config['access_token'])) {
$this->httpHeaders['X-Shopify-Access-Token'] = $config['access_token']; $this->httpHeaders['X-Shopify-Access-Token'] = $config['access_token'];
} elseif (!isset($config['access_token'])) { } elseif (!isset($config['access_token'])) {
throw new Exception("请设置access_token值"); throw new Exception("请设置access_token值");
} }
} else { } else {
if (isset($config['api_password'])) { if (isset($config['api_password'])) {
$this->httpHeaders['X-Shopify-Access-Token'] = $config['api_password']; $this->httpHeaders['X-Shopify-Access-Token'] = $config['api_password'];
} elseif (!isset($config['api_password'])) { } elseif (!isset($config['api_password'])) {
throw new Exception("请设置api_password值"); throw new Exception("请设置api_password值");
} }
} }
} }
/** /**
* 调用子集资源 * 调用子集资源
* @param $childName * @param $childName
* @return mixed * @return mixed
*/ */
public function __get($childName) public function __get($childName)
{ {
return $this->$childName(); return $this->$childName();
} }
/** /**
* 调用自定义方法 * 调用自定义方法
* @param $name * @param $name
* @param $arguments * @param $arguments
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function __call($name, $arguments) public function __call($name, $arguments)
{ {
if (ctype_upper($name[0])) { if (ctype_upper($name[0])) {
$childKey = array_search($name, $this->childResource); $childKey = array_search($name, $this->childResource);
if ($childKey === false) { if ($childKey === false) {
throw new Exception(" $name 不属于 {$this->getResourceName()}"); throw new Exception(" $name 不属于 {$this->getResourceName()}");
} }
$childClassName = !is_numeric($childKey) ? $childKey : $name; $childClassName = !is_numeric($childKey) ? $childKey : $name;
$childClass = __NAMESPACE__ . "\\" . $childClassName; $childClass = __NAMESPACE__ . "\\" . $childClassName;
$resourceID = !empty($arguments) ? $arguments[0] : null; $resourceID = !empty($arguments) ? $arguments[0] : null;
return new $childClass($this->config, $resourceID, $this->resourceUrl); return new $childClass($this->config, $resourceID, $this->resourceUrl);
} else { } else {
$actionMaps = [ $actionMaps = [
'post' => 'customPostActions', 'post' => 'customPostActions',
'put' => 'customPutActions', 'put' => 'customPutActions',
'get' => 'customGetActions', 'get' => 'customGetActions',
'delete' => 'customDeleteActions', 'delete' => 'customDeleteActions',
]; ];
//Get the array key for the action in the actions array //Get the array key for the action in the actions array
foreach ($actionMaps as $httpMethod => $actionArrayKey) { foreach ($actionMaps as $httpMethod => $actionArrayKey) {
$actionKey = array_search($name, $this->$actionArrayKey); $actionKey = array_search($name, $this->$actionArrayKey);
if ($actionKey !== false) break; if ($actionKey !== false) break;
} }
if ($actionKey === false) { if ($actionKey === false) {
throw new Exception("No action named $name is defined for " . $this->getResourceName()); throw new Exception("No action named $name is defined for " . $this->getResourceName());
} }
//If any associative key is given to the action, then it will be considered as the method name, //If any associative key is given to the action, then it will be considered as the method name,
//otherwise the action name will be the method name //otherwise the action name will be the method name
$customAction = !is_numeric($actionKey) ? $actionKey : $name; $customAction = !is_numeric($actionKey) ? $actionKey : $name;
//Get the first argument if provided with the method call //Get the first argument if provided with the method call
$methodArgument = !empty($arguments) ? $arguments[0] : []; $methodArgument = !empty($arguments) ? $arguments[0] : [];
//Url parameters //Url parameters
$urlParams = []; $urlParams = [];
//Data body //Data body
$dataArray = []; $dataArray = [];
//Consider the argument as url parameters for get and delete request //Consider the argument as url parameters for get and delete request
//and data array for post and put request //and data array for post and put request
if ($httpMethod == 'post' || $httpMethod == 'put') { if ($httpMethod == 'post' || $httpMethod == 'put') {
$dataArray = $methodArgument; $dataArray = $methodArgument;
} else { } else {
$urlParams = $methodArgument; $urlParams = $methodArgument;
} }
$url = $this->generateUrl($urlParams, null, $customAction); $url = $this->generateUrl($urlParams, null, $customAction);
if ($httpMethod == 'post' || $httpMethod == 'put') { if ($httpMethod == 'post' || $httpMethod == 'put') {
return $this->$httpMethod($dataArray, $url, false); return $this->$httpMethod($dataArray, $url, false);
} else { } else {
return $this->$httpMethod($dataArray, $url); return $this->$httpMethod($dataArray, $url);
} }
} }
} }
private function getResourceName() private function getResourceName()
{ {
return substr(get_called_class(), strrpos(get_called_class(), '\\') + 1); return substr(get_called_class(), strrpos(get_called_class(), '\\') + 1);
} }
public function generateUrl($urlParams = [], $id = null, $customAction = null) public function generateUrl($urlParams = [], $id = null, $customAction = null)
{ {
$resourceUrl = $this->resourceUrl; $resourceUrl = $this->resourceUrl;
if ($id) { if ($id) {
if ($this->id) { if ($this->id) {
if ($id !== $this->id) { if ($id !== $this->id) {
$resourceUrl = str_replace($this->id, $id, $this->resourceUrl); $resourceUrl = str_replace($this->id, $id, $this->resourceUrl);
} }
} else { } else {
$resourceUrl = $this->resourceUrl . "/$id"; $resourceUrl = $this->resourceUrl . "/$id";
} }
} }
return $resourceUrl . ($customAction ? "/$customAction" : '') . '.json' . (!empty($urlParams) ? '?' . http_build_query($urlParams) : ''); return $resourceUrl . ($customAction ? "/$customAction" : '') . '.json' . (!empty($urlParams) ? '?' . http_build_query($urlParams) : '');
} }
/** /**
* 获取数量 * 获取数量
* @param array $urlParams * @param array $urlParams
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function count($urlParams = []) public function count($urlParams = [])
{ {
if (!$this->countEnabled) { if (!$this->countEnabled) {
throw new Exception("当前类{$this->getResourceName()}不支持count()方法"); throw new Exception("当前类{$this->getResourceName()}不支持count()方法");
} }
$url = $this->generateUrl($urlParams, null, 'count'); $url = $this->generateUrl($urlParams, null, 'count');
return $this->get([], $url, 'count'); return $this->get([], $url, 'count');
} }
/** /**
* @param array $urlParams * @param array $urlParams
* @param null $url * @param null $url
* @param null $dataKey * @param null $dataKey
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function get($urlParams = [], $url = null, $dataKey = null) public function get($urlParams = [], $url = null, $dataKey = null)
{ {
if (!$url) $url = $this->generateUrl($urlParams); if (!$url) $url = $this->generateUrl($urlParams);
$response = $this->httpRequestJson->get($url, $this->httpHeaders); $response = $this->httpRequestJson->get($url, $this->httpHeaders);
if (!$dataKey) $dataKey = $this->id ? $this->resourceKey : $this->pluralizeKey; if (!$dataKey) $dataKey = $this->id ? $this->resourceKey : $this->pluralizeKey;
return $this->processResponse($response, $dataKey); return $this->processResponse($response, $dataKey);
} }
/** /**
* 分页 * 分页
* @param null $url * @param null $url
* @param array $urlParams * @param array $urlParams
* @return mixed ['data' => [数据], 'next_link' => '下一页链接'] * @return mixed ['data' => [数据], 'next_link' => '下一页链接']
* @throws Exception * @throws Exception
*/ */
public function page($url = null, $urlParams = []) public function page($url = null, $urlParams = [])
{ {
if (!$url) $url = $this->generateUrl($urlParams); if (!$url) $url = $this->generateUrl($urlParams);
$response = $this->httpRequestJson->get($url, $this->httpHeaders); $response = $this->httpRequestJson->get($url, $this->httpHeaders);
return $this->processPageResponse($response, $this->pluralizeKey); return $this->processPageResponse($response, $this->pluralizeKey);
} }
/** /**
* 根据id获取一条数据 * 根据id获取一条数据
* @param $id * @param $id
* @param array $urlParams * @param array $urlParams
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function show($id, $urlParams = []) public function show($id, $urlParams = [])
{ {
$url = $this->generateUrl($urlParams, $id); $url = $this->generateUrl($urlParams, $id);
$response = $this->httpRequestJson->get($url, $this->httpHeaders); $response = $this->httpRequestJson->get($url, $this->httpHeaders);
return $this->processResponse($response, $this->resourceKey); return $this->processResponse($response, $this->resourceKey);
} }
/** /**
* @param $dataArray * @param $dataArray
* @param null $url * @param null $url
* @param bool $wrapData * @param bool $wrapData
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function post($dataArray, $url = null, $wrapData = true) public function post($dataArray, $url = null, $wrapData = true)
{ {
if (!$url) $url = $this->generateUrl(); if (!$url) $url = $this->generateUrl();
if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray); if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray);
$response = $this->httpRequestJson->post($url, $dataArray, $this->httpHeaders); $response = $this->httpRequestJson->post($url, $dataArray, $this->httpHeaders);
return $this->processResponse($response, $this->resourceKey); return $this->processResponse($response, $this->resourceKey);
} }
/** /**
* @param int|string $id * @param int|string $id
* @param $dataArray * @param $dataArray
* @param null $url * @param null $url
* @param bool $wrapData * @param bool $wrapData
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function put($id, $dataArray, $url = null, $wrapData = true) public function put($id, $dataArray, $url = null, $wrapData = true)
{ {
if (!$url) $url = $this->generateUrl([], $id); if (!$url) $url = $this->generateUrl([], $id);
if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray); if ($wrapData && !empty($dataArray)) $dataArray = $this->wrapData($dataArray);
$response = $this->httpRequestJson->put($url, $dataArray, $this->httpHeaders); $response = $this->httpRequestJson->put($url, $dataArray, $this->httpHeaders);
return $this->processResponse($response, $this->resourceKey); return $this->processResponse($response, $this->resourceKey);
} }
/** /**
* @param int|string $id * @param int|string $id
* @param array $urlParams * @param array $urlParams
* @param null $url * @param null $url
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function delete($id = null, $urlParams = [], $url = null) public function delete($id = null, $urlParams = [], $url = null)
{ {
if (!$url) $url = $this->generateUrl($urlParams, $id); if (!$url) $url = $this->generateUrl($urlParams, $id);
$response = $this->httpRequestJson->delete($url, $this->httpHeaders); $response = $this->httpRequestJson->delete($url, $this->httpHeaders);
return $this->processResponse($response); return $this->processResponse($response);
} }
protected function wrapData($dataArray, $dataKey = null) protected function wrapData($dataArray, $dataKey = null)
{ {
if (!$dataKey) $dataKey = $this->resourceKey; if (!$dataKey) $dataKey = $this->resourceKey;
return [$dataKey => $dataArray]; return [$dataKey => $dataArray];
} }
protected function castString($array) protected function castString($array)
{ {
if (!is_array($array)) return (string)$array; if (!is_array($array)) return (string)$array;
$string = ''; $string = '';
$i = 0; $i = 0;
foreach ($array as $key => $val) { foreach ($array as $key => $val) {
$string .= ($i === $key ? '' : "$key - ") . $this->castString($val) . ', '; $string .= ($i === $key ? '' : "$key - ") . $this->castString($val) . ', ';
$i++; $i++;
} }
$string = rtrim($string, ', '); $string = rtrim($string, ', ');
return $string; return $string;
} }
/** /**
* 处理响应 * 处理响应
* @param array $response * @param array $response
* @param null $dataKey * @param null $dataKey
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function processResponse($response, $dataKey = null) public function processResponse($response, $dataKey = null)
{ {
[$code, , $content] = $response; [$code, , $content] = $response;
$content = json_decode($content, true); $content = json_decode($content, true);
if (isset($content['errors'])) { if (isset($content['errors'])) {
throw new Exception($this->castString($content['errors']), $code); throw new Exception($this->castString($content['errors']), $code);
} }
if ($dataKey && isset($content[$dataKey])) { if ($dataKey && isset($content[$dataKey])) {
return $content[$dataKey]; return $content[$dataKey];
} else { } else {
return $content; return $content;
} }
} }
/** /**
* 处理响应 * 处理响应
* @param ResponseInterface $response * @param ResponseInterface $response
* @param null $dataKey * @param null $dataKey
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function processPageResponse($response, $dataKey = null) public function processPageResponse($response, $dataKey = null)
{ {
[$code, $headers, $content] = $response; [$code, $headers, $content] = $response;
$content = json_decode($content, true); $content = json_decode($content, true);
$link = $this->getLink($headers); $link = $this->getLink($headers);
if (isset($content['errors'])) { if (isset($content['errors'])) {
throw new Exception($this->castString($content['errors']), $code); throw new Exception($this->castString($content['errors']), $code);
} }
if ($dataKey && isset($content[$dataKey])) { if ($dataKey && isset($content[$dataKey])) {
$data = $content[$dataKey]; $data = $content[$dataKey];
} else { } else {
$data = $content; $data = $content;
} }
return ['data' => $data, 'next_link' => $link]; return ['data' => $data, 'next_link' => $link];
} }
public function getLink($header, $type = 'next') public function getLink($header, $type = 'next')
{ {
if (!empty($header['x-shopify-api-version'][0]) && $header['x-shopify-api-version'][0] < '2019-07') { if (!empty($header['x-shopify-api-version'][0]) && $header['x-shopify-api-version'][0] < '2019-07') {
return null; return null;
} }
if (!empty($header['link'][0])) { if (!empty($header['link'][0])) {
$headerLinks = $header['link'][0]; $headerLinks = $header['link'][0];
if (stristr($headerLinks, '; rel="' . $type . '"') > -1) { if (stristr($headerLinks, '; rel="' . $type . '"') > -1) {
$headerLinks = explode(',', $headerLinks); $headerLinks = explode(',', $headerLinks);
foreach ($headerLinks as $headerLink) { foreach ($headerLinks as $headerLink) {
if (stristr($headerLink, '; rel="' . $type . '"') === -1) { if (stristr($headerLink, '; rel="' . $type . '"') === -1) {
continue; continue;
} }
$pattern = '#<(.*?)>; rel="' . $type . '"#m'; $pattern = '#<(.*?)>; rel="' . $type . '"#m';
preg_match($pattern, $headerLink, $linkResponseHeaders); preg_match($pattern, $headerLink, $linkResponseHeaders);
if ($linkResponseHeaders) { if ($linkResponseHeaders) {
return $linkResponseHeaders[1]; return $linkResponseHeaders[1];
} }
} }
} }
} }
return null; return null;
} }
} }
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: Zero * User: Zero
* Date: 2021/01/08 * Date: 2021/01/08
* Time: 09:34:30 * Time: 09:34:30
*/ */
namespace Meibuyu\Micro\Shopify\lib; namespace Meibuyu\Micro\Shopify\lib;
use Exception; use Exception;
use Meibuyu\Micro\Shopify\tools\HttpRequestGraphQL; use Meibuyu\Micro\Shopify\tools\HttpRequestGraphQL;
/** /**
* Class GraphQL * Class GraphQL
* @package Meibuyu\Micro\Shopify\lib * @package Meibuyu\Micro\Shopify\lib
*/ */
class GraphQL extends AbstractShopify class GraphQL extends AbstractShopify
{ {
protected $resourceKey = 'graphql'; protected $resourceKey = 'graphql';
protected $pluralizeKey = 'graphql'; protected $pluralizeKey = 'graphql';
public function post($graphQL, $url = null, $wrapData = false, $variables = null) public function post($graphQL, $url = null, $wrapData = false, $variables = null)
{ {
if (!$url) $url = $this->generateUrl(); if (!$url) $url = $this->generateUrl();
$response = HttpRequestGraphQL::post($url, $graphQL, $this->httpHeaders, $variables); $response = HttpRequestGraphQL::post($url, $graphQL, $this->httpHeaders, $variables);
return $this->processResponse($response); return $this->processResponse($response);
} }
public function get($urlParams = array(), $url = null, $dataKey = null) public function get($urlParams = array(), $url = null, $dataKey = null)
{ {
throw new Exception("GraphQL 只支持 POST 请求!"); throw new Exception("GraphQL 只支持 POST 请求!");
} }
public function put($id, $dataArray, $url = null, $wrapData = true) public function put($id, $dataArray, $url = null, $wrapData = true)
{ {
throw new Exception("GraphQL 只支持 POST 请求!"); throw new Exception("GraphQL 只支持 POST 请求!");
} }
public function delete($id = null, $urlParams = [], $url = null) public function delete($id = null, $urlParams = [], $url = null)
{ {
throw new Exception("GraphQL 只支持 POST 请求!"); throw new Exception("GraphQL 只支持 POST 请求!");
} }
} }
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
<?php <?php
namespace Meibuyu\Micro\Shopify\tools; namespace Meibuyu\Micro\Shopify\tools;
use Exception; use Exception;
class CurlRequest class CurlRequest
{ {
protected static function init($url, $httpHeaders = []) protected static function init($url, $httpHeaders = [])
{ {
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100); // 设置超时限制防止死循环 curl_setopt($ch, CURLOPT_TIMEOUT, 100); // 设置超时限制防止死循环
curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHPClassic/PHPShopify'); curl_setopt($ch, CURLOPT_USERAGENT, 'PHPClassic/PHPShopify');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
$headers = []; $headers = [];
foreach ($httpHeaders as $key => $value) { foreach ($httpHeaders as $key => $value) {
$headers[] = "$key: $value"; $headers[] = "$key: $value";
} }
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
return $ch; return $ch;
} }
/** /**
* @param $url * @param $url
* @param array $httpHeaders * @param array $httpHeaders
* @return array * @return array
* @throws Exception * @throws Exception
* @author zero * @author zero
*/ */
public static function get($url, $httpHeaders = []) public static function get($url, $httpHeaders = [])
{ {
$ch = self::init($url, $httpHeaders); $ch = self::init($url, $httpHeaders);
return self::processRequest($ch); return self::processRequest($ch);
} }
/** /**
* @param $url * @param $url
* @param $data * @param $data
* @param array $httpHeaders * @param array $httpHeaders
* @return array * @return array
* @throws Exception * @throws Exception
* @author zero * @author zero
*/ */
public static function post($url, $data, $httpHeaders = []) public static function post($url, $data, $httpHeaders = [])
{ {
$ch = self::init($url, $httpHeaders); $ch = self::init($url, $httpHeaders);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
return self::processRequest($ch); return self::processRequest($ch);
} }
/** /**
* @param $url * @param $url
* @param $data * @param $data
* @param array $httpHeaders * @param array $httpHeaders
* @return array * @return array
* @throws Exception * @throws Exception
* @author zero * @author zero
*/ */
public static function put($url, $data, $httpHeaders = []) public static function put($url, $data, $httpHeaders = [])
{ {
$ch = self::init($url, $httpHeaders); $ch = self::init($url, $httpHeaders);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
return self::processRequest($ch); return self::processRequest($ch);
} }
/** /**
* @param $url * @param $url
* @param array $httpHeaders * @param array $httpHeaders
* @return array * @return array
* @throws Exception * @throws Exception
* @author zero * @author zero
*/ */
public static function delete($url, $httpHeaders = []) public static function delete($url, $httpHeaders = [])
{ {
$ch = self::init($url, $httpHeaders); $ch = self::init($url, $httpHeaders);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
return self::processRequest($ch); return self::processRequest($ch);
} }
/** /**
* @param $ch * @param $ch
* @return array * @return array
* @throws Exception * @throws Exception
* @author zero * @author zero
*/ */
protected static function processRequest($ch) protected static function processRequest($ch)
{ {
$output = curl_exec($ch); $output = curl_exec($ch);
$response = new CurlResponse($output); $response = new CurlResponse($output);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// if ($httpCode == 429) { // if ($httpCode == 429) {
// $limitHeader = explode('/', $response->getHeader('X-Shopify-Shop-Api-Call-Limit')[0], 2); // $limitHeader = explode('/', $response->getHeader('X-Shopify-Shop-Api-Call-Limit')[0], 2);
// if (isset($limitHeader[1]) && $limitHeader[0] < $limitHeader[1]) { // if (isset($limitHeader[1]) && $limitHeader[0] < $limitHeader[1]) {
// throw new Exception($response->getBody()); // throw new Exception($response->getBody());
// } // }
// } // }
if (curl_errno($ch)) { if (curl_errno($ch)) {
throw new Exception(curl_errno($ch) . ' : ' . curl_error($ch)); throw new Exception(curl_errno($ch) . ' : ' . curl_error($ch));
} }
curl_close($ch); curl_close($ch);
return [$httpCode, $response->getHeaders(), $response->getBody()]; return [$httpCode, $response->getHeaders(), $response->getBody()];
} }
} }
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: Zero * User: Zero
* Date: 2021/06/09 * Date: 2021/06/09
* Time: 10:14:32 * Time: 10:14:32
*/ */
namespace Meibuyu\Micro\Tools; namespace Meibuyu\Micro\Tools;
use Hyperf\Logger\Logger; use Hyperf\Logger\Logger;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter; use Monolog\Formatter\LineFormatter;
use Monolog\Handler\FormattableHandlerInterface; use Monolog\Handler\FormattableHandlerInterface;
use Monolog\Handler\HandlerInterface; use Monolog\Handler\HandlerInterface;
use Monolog\Handler\RotatingFileHandler; use Monolog\Handler\RotatingFileHandler;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
/** /**
* Class Log * Class Log
* @package App\Services * @package App\Services
* @method static emergency($message, string $name = 'app') * @method static emergency($message, string $name = 'app')
* @method static alert($message, string $name = 'app') * @method static alert($message, string $name = 'app')
* @method static critical($message, string $name = 'app') * @method static critical($message, string $name = 'app')
* @method static error($message, string $name = 'app') * @method static error($message, string $name = 'app')
* @method static warning($message, string $name = 'app') * @method static warning($message, string $name = 'app')
* @method static notice($message, string $name = 'app') * @method static notice($message, string $name = 'app')
* @method static info($message, string $name = 'app') * @method static info($message, string $name = 'app')
* @method static debug($message, string $name = 'app') * @method static debug($message, string $name = 'app')
*/ */
class Log class Log
{ {
/** /**
* @var LoggerInterface * @var LoggerInterface
*/ */
protected static $logs; protected static $logs;
/** /**
* @return LoggerInterface * @return LoggerInterface
*/ */
public static function log($channel = 'app') public static function log($channel = 'app')
{ {
if (!isset(self::$logs[$channel])) { if (!isset(self::$logs[$channel])) {
self::$logs[$channel] = make(Logger::class, [ self::$logs[$channel] = make(Logger::class, [
'name' => $channel, 'name' => $channel,
'handlers' => self::handlers($channel), 'handlers' => self::handlers($channel),
]); ]);
} }
return self::$logs[$channel]; return self::$logs[$channel];
} }
protected static function handlers($channel): array protected static function handlers($channel): array
{ {
$handlerConfigs = [ $handlerConfigs = [
[ [
'class' => RotatingFileHandler::class, 'class' => RotatingFileHandler::class,
'constructor' => [ 'constructor' => [
'filename' => BASE_PATH . "/runtime/logs/$channel.log", 'filename' => BASE_PATH . "/runtime/logs/$channel.log",
'level' => Logger::DEBUG, 'level' => Logger::DEBUG,
], ],
'formatter' => [ 'formatter' => [
'class' => LineFormatter::class, 'class' => LineFormatter::class,
'constructor' => [ 'constructor' => [
'format' => "[%datetime%] %channel%.%level_name%: %message%\n", 'format' => "[%datetime%] %channel%.%level_name%: %message%\n",
'dateFormat' => 'Y-m-d H:i:s', 'dateFormat' => 'Y-m-d H:i:s',
'allowInlineLineBreaks' => true, 'allowInlineLineBreaks' => true,
], ],
], ],
], ],
]; ];
$handlers = []; $handlers = [];
foreach ($handlerConfigs as $value) { foreach ($handlerConfigs as $value) {
$formatterConfig = $value['formatter']; $formatterConfig = $value['formatter'];
/** @var HandlerInterface $handler */ /** @var HandlerInterface $handler */
$handler = make($value['class'], $value['constructor']); $handler = make($value['class'], $value['constructor']);
if ($handler instanceof FormattableHandlerInterface) { if ($handler instanceof FormattableHandlerInterface) {
$formatterClass = $formatterConfig['class']; $formatterClass = $formatterConfig['class'];
$formatterConstructor = $formatterConfig['constructor']; $formatterConstructor = $formatterConfig['constructor'];
/** @var FormatterInterface $formatter */ /** @var FormatterInterface $formatter */
$formatter = make($formatterClass, $formatterConstructor); $formatter = make($formatterClass, $formatterConstructor);
$handler->setFormatter($formatter); $handler->setFormatter($formatter);
} }
$handlers[] = $handler; $handlers[] = $handler;
} }
return $handlers; return $handlers;
} }
public static function __callStatic($name, $arguments) public static function __callStatic($name, $arguments)
{ {
$msg = $arguments[0]; $msg = $arguments[0];
if (is_array($msg)) { if (is_array($msg)) {
$msg = var_export($msg, true); $msg = var_export($msg, true);
} }
$channel = $arguments[1] ?? 'app'; $channel = $arguments[1] ?? 'app';
return static::log($channel)->{$name}($msg); return static::log($channel)->{$name}($msg);
} }
} }
\ No newline at end of file
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
<?php <?php
use Hyperf\Cache\Listener\DeleteListenerEvent; use Hyperf\Cache\Listener\DeleteListenerEvent;
use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface; use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Logger\Logger; use Hyperf\Logger\Logger;
use Hyperf\Redis\Redis; use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext; use Hyperf\Utils\ApplicationContext;
use Monolog\Formatter\LineFormatter; use Monolog\Formatter\LineFormatter;
use Monolog\Handler\FirePHPHandler; use Monolog\Handler\FirePHPHandler;
use Monolog\Handler\StreamHandler; use Monolog\Handler\StreamHandler;
use Psr\EventDispatcher\EventDispatcherInterface; use Psr\EventDispatcher\EventDispatcherInterface;
/** /**
* 容器实例 * 容器实例
*/ */
if (!function_exists('container')) { if (!function_exists('container')) {
function container($key = null) function container($key = null)
{ {
if (is_null($key)) { if (is_null($key)) {
return ApplicationContext::getContainer(); return ApplicationContext::getContainer();
} else { } else {
return ApplicationContext::getContainer()->get($key); return ApplicationContext::getContainer()->get($key);
} }
} }
} }
if (!function_exists('redis')) { if (!function_exists('redis')) {
/** /**
* 获取redis客户端实例 * 获取redis客户端实例
* @return Redis|mixed * @return Redis|mixed
*/ */
function redis() function redis()
{ {
return container(Redis::class); return container(Redis::class);
} }
} }
/** /**
* token * token
*/ */
if (!function_exists('token')) { if (!function_exists('token')) {
function token() function token()
{ {
$token = request()->getHeader('Authorization')[0] ?? ''; $token = request()->getHeader('Authorization')[0] ?? '';
if (strlen($token) > 0) { if (strlen($token) > 0) {
$token = ucfirst($token); $token = ucfirst($token);
$arr = explode('Bearer ', $token); $arr = explode('Bearer ', $token);
$token = $arr[1] ?? ''; $token = $arr[1] ?? '';
if (strlen($token) > 0) { if (strlen($token) > 0) {
return $token; return $token;
} }
} }
return false; return false;
} }
} }
if (!function_exists('request')) { if (!function_exists('request')) {
/** /**
* 请求实例 * 请求实例
* @param array|string|null $key * @param array|string|null $key
* @param mixed $default * @param mixed $default
* @return RequestInterface|string|array|mixed * @return RequestInterface|string|array|mixed
*/ */
function request($key = null, $default = null) function request($key = null, $default = null)
{ {
if (is_null($key)) { if (is_null($key)) {
return container(RequestInterface::class); return container(RequestInterface::class);
} }
if (is_array($key)) { if (is_array($key)) {
return container(RequestInterface::class)->inputs($key); return container(RequestInterface::class)->inputs($key);
} }
$value = container(RequestInterface::class)->input($key); $value = container(RequestInterface::class)->input($key);
return is_null($value) ? value($default) : $value; return is_null($value) ? value($default) : $value;
} }
} }
if (!function_exists('response')) { if (!function_exists('response')) {
/** /**
* 响应实例 * 响应实例
* @return mixed|ResponseInterface * @return mixed|ResponseInterface
*/ */
function response() function response()
{ {
return container(ResponseInterface::class); return container(ResponseInterface::class);
} }
} }
if (!function_exists('success')) { if (!function_exists('success')) {
/** /**
* 成功响应实例 * 成功响应实例
* @param string $msg * @param string $msg
* @param mixed $data * @param mixed $data
* @param int $code * @param int $code
* @return mixed * @return mixed
*/ */
function success($msg = '', $data = null, $code = 200) function success($msg = '', $data = null, $code = 200)
{ {
return response()->json([ return response()->json([
'msg' => $msg, 'msg' => $msg,
'data' => $data, 'data' => $data,
'code' => $code 'code' => $code
]); ]);
} }
} }
if (!function_exists('fail')) { if (!function_exists('fail')) {
/** /**
* 失败响应实例 * 失败响应实例
* @param string $msg * @param string $msg
* @param mixed $data * @param mixed $data
* @param int $code * @param int $code
* @return mixed * @return mixed
*/ */
function fail($msg = '', $data = null, $code = 400) function fail($msg = '', $data = null, $code = 400)
{ {
return response()->json([ return response()->json([
'msg' => $msg, 'msg' => $msg,
'data' => $data, 'data' => $data,
'code' => $code 'code' => $code
]); ]);
} }
} }
if (!function_exists('download')) { if (!function_exists('download')) {
/** /**
* 文件流下载文件 * 文件流下载文件
* @param string $filePath 文件路径 * @param string $filePath 文件路径
* @param string $showName 下载后展示的名称 * @param string $showName 下载后展示的名称
* @return mixed * @return mixed
*/ */
function download($filePath = '', $showName = '') function download($filePath = '', $showName = '')
{ {
return response()->download($filePath, urlencode($showName)); return response()->download($filePath, urlencode($showName));
} }
} }
if (!function_exists('decimal_to_abc')) { if (!function_exists('decimal_to_abc')) {
/** /**
* 数字转换对应26个字母 * 数字转换对应26个字母
* @param $num * @param $num
* @return string * @return string
* @deprecated 此方法废弃,请使用int_to_chr() * @deprecated 此方法废弃,请使用int_to_chr()
*/ */
function decimal_to_abc($num) function decimal_to_abc($num)
{ {
$str = ""; $str = "";
$ten = $num; $ten = $num;
if ($ten == 0) return "A"; if ($ten == 0) return "A";
while ($ten != 0) { while ($ten != 0) {
$x = $ten % 26; $x = $ten % 26;
$str .= chr(65 + $x); $str .= chr(65 + $x);
$ten = intval($ten / 26); $ten = intval($ten / 26);
} }
return strrev($str); return strrev($str);
} }
} }
if (!function_exists('diff_between_two_days')) { if (!function_exists('diff_between_two_days')) {
/** /**
* 计算两个日期之间相差的天数 * 计算两个日期之间相差的天数
* @param $day1 * @param $day1
* @param $day2 * @param $day2
* @return float|int * @return float|int
*/ */
function diff_between_two_days($day1, $day2) function diff_between_two_days($day1, $day2)
{ {
$second1 = strtotime($day1); $second1 = strtotime($day1);
$second2 = strtotime($day2); $second2 = strtotime($day2);
return round((abs($second1 - $second2) / 86400), 0); return round((abs($second1 - $second2) / 86400), 0);
} }
} }
if (!function_exists('decimals_to_percentage')) { if (!function_exists('decimals_to_percentage')) {
/** /**
* 将小数转换百分数 * 将小数转换百分数
* @param float $decimals 小数 * @param float $decimals 小数
* @param int $num 保留小数位 * @param int $num 保留小数位
* @return string * @return string
*/ */
function decimals_to_percentage($decimals, $num = 2) function decimals_to_percentage($decimals, $num = 2)
{ {
return sprintf("%01." . $num . "f", $decimals * 100) . '%'; return sprintf("%01." . $num . "f", $decimals * 100) . '%';
} }
} }
if (!function_exists('calculate_grade')) { if (!function_exists('calculate_grade')) {
/** /**
* *
* 计算一个数的区间范围等级 * 计算一个数的区间范围等级
* @param array $range 区间范围(从大到小排列) * @param array $range 区间范围(从大到小排列)
* @param $num * @param $num
* @return mixed|void * @return mixed|void
*/ */
function calculate_grade($range, $num) function calculate_grade($range, $num)
{ {
$max = max($range); $max = max($range);
if ($num >= $max) { if ($num >= $max) {
return count($range); return count($range);
} }
foreach ($range as $k => $v) { foreach ($range as $k => $v) {
if ($num < $v) { if ($num < $v) {
return $k; return $k;
} }
} }
} }
} }
if (!function_exists('convertAmountToCn')) { if (!function_exists('convertAmountToCn')) {
/** /**
* 2 * 将数值金额转换为中文大写金额 * 2 * 将数值金额转换为中文大写金额
* 3 * @param $amount float 金额(支持到分) * 3 * @param $amount float 金额(支持到分)
* 4 * @param $type int 补整类型,0:到角补整;1:到元补整 * 4 * @param $type int 补整类型,0:到角补整;1:到元补整
* 5 * @return mixed 中文大写金额 * 5 * @return mixed 中文大写金额
* 6 */ * 6 */
function convertAmountToCn($amount, $type = 1) function convertAmountToCn($amount, $type = 1)
{ {
// 判断输出的金额是否为数字或数字字符串 // 判断输出的金额是否为数字或数字字符串
if (!is_numeric($amount)) { if (!is_numeric($amount)) {
return "要转换的金额只能为数字!"; return "要转换的金额只能为数字!";
} }
// 金额为0,则直接输出"零元整" // 金额为0,则直接输出"零元整"
if ($amount == 0) { if ($amount == 0) {
return "人民币零元整"; return "人民币零元整";
} }
// 金额不能为负数 // 金额不能为负数
if ($amount < 0) { if ($amount < 0) {
return "要转换的金额不能为负数!"; return "要转换的金额不能为负数!";
} }
// 金额不能超过万亿,即12位 // 金额不能超过万亿,即12位
if (strlen($amount) > 12) { if (strlen($amount) > 12) {
return "要转换的金额不能为万亿及更高金额!"; return "要转换的金额不能为万亿及更高金额!";
} }
// 预定义中文转换的数组 // 预定义中文转换的数组
$digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'); $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
// 预定义单位转换的数组 // 预定义单位转换的数组
$position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元'); $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');
// 将金额的数值字符串拆分成数组 // 将金额的数值字符串拆分成数组
$amountArr = explode('.', $amount); $amountArr = explode('.', $amount);
// 将整数位的数值字符串拆分成数组 // 将整数位的数值字符串拆分成数组
$integerArr = str_split($amountArr[0], 1); $integerArr = str_split($amountArr[0], 1);
// 将整数部分替换成大写汉字 // 将整数部分替换成大写汉字
$result = '人民币'; $result = '人民币';
$integerArrLength = count($integerArr); // 整数位数组的长度 $integerArrLength = count($integerArr); // 整数位数组的长度
$positionLength = count($position); // 单位数组的长度 $positionLength = count($position); // 单位数组的长度
for ($i = 0; $i < $integerArrLength; $i++) { for ($i = 0; $i < $integerArrLength; $i++) {
// 如果数值不为0,则正常转换 // 如果数值不为0,则正常转换
if ($integerArr[$i] != 0) { if ($integerArr[$i] != 0) {
$result = $result . $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i]; $result = $result . $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
} else { } else {
// 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位 // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
if (($positionLength - $integerArrLength + $i + 1) % 4 == 0) { if (($positionLength - $integerArrLength + $i + 1) % 4 == 0) {
$result = $result . $position[$positionLength - $integerArrLength + $i]; $result = $result . $position[$positionLength - $integerArrLength + $i];
} }
} }
} }
// 如果小数位也要转换 // 如果小数位也要转换
if ($type == 0) { if ($type == 0) {
// 将小数位的数值字符串拆分成数组 // 将小数位的数值字符串拆分成数组
$decimalArr = str_split($amountArr[1], 1); $decimalArr = str_split($amountArr[1], 1);
// 将角替换成大写汉字. 如果为0,则不替换 // 将角替换成大写汉字. 如果为0,则不替换
if ($decimalArr[0] != 0) { if ($decimalArr[0] != 0) {
$result = $result . $digital[$decimalArr[0]] . '角'; $result = $result . $digital[$decimalArr[0]] . '角';
} }
// 将分替换成大写汉字. 如果为0,则不替换 // 将分替换成大写汉字. 如果为0,则不替换
if ($decimalArr[1] != 0) { if ($decimalArr[1] != 0) {
$result = $result . $digital[$decimalArr[1]] . '分'; $result = $result . $digital[$decimalArr[1]] . '分';
} }
} else { } else {
$result = $result . '整'; $result = $result . '整';
} }
return $result; return $result;
} }
} }
if (!function_exists('today')) { if (!function_exists('today')) {
/** /**
* Create a new Carbon instance for the current time. * Create a new Carbon instance for the current time.
* @return false|string * @return false|string
*/ */
function today() function today()
{ {
return date('Y-m-d', time()); return date('Y-m-d', time());
} }
} }
if (!function_exists('now')) { if (!function_exists('now')) {
/** /**
* Create a new Carbon instance for the current time. * Create a new Carbon instance for the current time.
* @return false|string * @return false|string
*/ */
function now() function now()
{ {
return date('Y-m-d H:i:s', time()); return date('Y-m-d H:i:s', time());
} }
} }
if (!function_exists('get_tree_id')) { if (!function_exists('get_tree_id')) {
/** /**
* @param array $array * @param array $array
* @param array $pid * @param array $pid
* @return array * @return array
*/ */
function get_tree_id(array $array, $pids = [0]) function get_tree_id(array $array, $pids = [0])
{ {
$list = []; $list = [];
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
if (in_array($value['pid'], $pids) || in_array($value['id'], $pids)) { if (in_array($value['pid'], $pids) || in_array($value['id'], $pids)) {
$list[] = $value['id']; $list[] = $value['id'];
unset($array[$key]); unset($array[$key]);
} }
} }
if ($list == []) return []; if ($list == []) return [];
$children = get_tree_id($array, $list); $children = get_tree_id($array, $list);
return array_merge($list, $children); return array_merge($list, $children);
} }
} }
if (!function_exists('list_go_tree')) { if (!function_exists('list_go_tree')) {
/** /**
* 列表转树状格式 * 列表转树状格式
* @param array $list * @param array $list
* @param string $pk * @param string $pk
* @param string $pid * @param string $pid
* @param string $children * @param string $children
* @return array * @return array
*/ */
function list_go_tree(array $list = [], $pk = 'id', $pid = 'parent_id', $children = 'children') function list_go_tree(array $list = [], $pk = 'id', $pid = 'parent_id', $children = 'children')
{ {
$tree = $refer = []; $tree = $refer = [];
// 创建基于主键的数组引用 // 创建基于主键的数组引用
foreach ($list as $key => $data) { foreach ($list as $key => $data) {
$refer[$data[$pk]] = &$list[$key]; $refer[$data[$pk]] = &$list[$key];
} }
foreach ($list as $key => $data) { foreach ($list as $key => $data) {
$parentId = $data[$pid]; $parentId = $data[$pid];
// 判断是否存在parent // 判断是否存在parent
if (isset($refer[$parentId])) { if (isset($refer[$parentId])) {
$parent = &$refer[$parentId]; $parent = &$refer[$parentId];
$parent[$children][] = &$list[$key]; $parent[$children][] = &$list[$key];
} else { } else {
$tree[] = &$list[$key]; $tree[] = &$list[$key];
} }
} }
return $tree; return $tree;
} }
} }
if (!function_exists('flushAnnotationCache')) { if (!function_exists('flushAnnotationCache')) {
/** /**
* 刷新注解缓存,清楚注解缓存 * 刷新注解缓存,清楚注解缓存
* @param string $listener * @param string $listener
* @param mixed $keys * @param mixed $keys
* @return bool * @return bool
*/ */
function flushAnnotationCache($listener, $keys) function flushAnnotationCache($listener, $keys)
{ {
$keys = is_array($keys) ? $keys : [$keys]; $keys = is_array($keys) ? $keys : [$keys];
$dispatcher = ApplicationContext::getContainer()->get(EventDispatcherInterface::class); $dispatcher = ApplicationContext::getContainer()->get(EventDispatcherInterface::class);
foreach ($keys as $key) { foreach ($keys as $key) {
$dispatcher->dispatch(new DeleteListenerEvent($listener, [$key])); $dispatcher->dispatch(new DeleteListenerEvent($listener, [$key]));
} }
return true; return true;
} }
} }
if (!function_exists('num_2_file_size')) { if (!function_exists('num_2_file_size')) {
/** /**
* 数字转文件大小 * 数字转文件大小
* @param $num * @param $num
* @return string * @return string
*/ */
function num_2_file_size($num) function num_2_file_size($num)
{ {
$p = 0; $p = 0;
$format = 'B'; $format = 'B';
if ($num > 0 && $num < 1024) { if ($num > 0 && $num < 1024) {
return number_format($num) . ' ' . $format; return number_format($num) . ' ' . $format;
} else if ($num >= 1024 && $num < pow(1024, 2)) { } else if ($num >= 1024 && $num < pow(1024, 2)) {
$p = 1; $p = 1;
$format = 'KB'; $format = 'KB';
} else if ($num >= pow(1024, 2) && $num < pow(1024, 3)) { } else if ($num >= pow(1024, 2) && $num < pow(1024, 3)) {
$p = 2; $p = 2;
$format = 'MB'; $format = 'MB';
} else if ($num >= pow(1024, 3) && $num < pow(1024, 4)) { } else if ($num >= pow(1024, 3) && $num < pow(1024, 4)) {
$p = 3; $p = 3;
$format = 'GB'; $format = 'GB';
} else if ($num >= pow(1024, 4) && $num < pow(1024, 5)) { } else if ($num >= pow(1024, 4) && $num < pow(1024, 5)) {
$p = 4; $p = 4;
$format = 'TB'; $format = 'TB';
} }
$num /= pow(1024, $p); $num /= pow(1024, $p);
return number_format($num, 2) . ' ' . $format; return number_format($num, 2) . ' ' . $format;
} }
} }
if (!function_exists('select_id_name')) { if (!function_exists('select_id_name')) {
function select_id_name($columns = []) function select_id_name($columns = [])
{ {
$columns = array_merge(['id', 'name'], $columns); $columns = array_merge(['id', 'name'], $columns);
return function ($q) use ($columns) { return function ($q) use ($columns) {
$q->select($columns); $q->select($columns);
}; };
} }
} }
if (!function_exists('get_week_start_and_end')) { if (!function_exists('get_week_start_and_end')) {
function get_week_start_and_end($time = '', $first = 1) function get_week_start_and_end($time = '', $first = 1)
{ {
//当前日期 //当前日期
if (!$time) $time = time(); if (!$time) $time = time();
$sdefaultDate = date("Y-m-d", $time); $sdefaultDate = date("Y-m-d", $time);
//$first =1 表示每周星期一为开始日期 0表示每周日为开始日期 //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
//获取当前周的第几天 周日是 0 周一到周六是 1 - 6 //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
$w = date('w', strtotime($sdefaultDate)); $w = date('w', strtotime($sdefaultDate));
//获取本周开始日期,如果$w是0,则表示周日,减去 6 天 //获取本周开始日期,如果$w是0,则表示周日,减去 6 天
$week_start = date('Y-m-d', strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days')); $week_start = date('Y-m-d', strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days'));
//本周结束日期 //本周结束日期
$week_end = date('Y-m-d', strtotime("$week_start +6 days")); $week_end = date('Y-m-d', strtotime("$week_start +6 days"));
return array("week_start" => $week_start, "week_end" => $week_end); return array("week_start" => $week_start, "week_end" => $week_end);
} }
} }
if (!function_exists('putLog')) { if (!function_exists('putLog')) {
/** /**
* description:记录日志 文件会生成在当前项目 /runtime/dev/ * description:记录日志 文件会生成在当前项目 /runtime/dev/
* author: fuyunnan * author: fuyunnan
* @param string|array $output 日志 内容 * @param string|array $output 日志 内容
* @param string $dir 目录 * @param string $dir 目录
* @param string $filename 文件名称 * @param string $filename 文件名称
* date: 2020/3/18 * date: 2020/3/18
* @return void * @return void
* @throws * @throws
*/ */
function put_log($output = 'out-mes', $filename = '', $dir = BASE_PATH . '/runtime/logs/dev/') function put_log($output = 'out-mes', $filename = '', $dir = BASE_PATH . '/runtime/logs/dev/')
{ {
!is_dir($dir) && !mkdir($dir, 0777, true); !is_dir($dir) && !mkdir($dir, 0777, true);
// 创建一个 Channel,参数 log 即为 Channel 的名字 // 创建一个 Channel,参数 log 即为 Channel 的名字
$log = make(Logger::class, ['']); $log = make(Logger::class, ['']);
// 创建两个 Handler,对应变量 $stream 和 $fire // 创建两个 Handler,对应变量 $stream 和 $fire
!$filename && $filename = date('Y-m-d', time()) . '.log'; !$filename && $filename = date('Y-m-d', time()) . '.log';
$stream = make(StreamHandler::class, [$dir . $filename, Logger::WARNING]); $stream = make(StreamHandler::class, [$dir . $filename, Logger::WARNING]);
$fire = make(FirePHPHandler::class); $fire = make(FirePHPHandler::class);
if (is_array($output)) { if (is_array($output)) {
$output = var_export($output, true); $output = var_export($output, true);
} }
$output = '[ ' . date('Y-m-d H:i:s', time()) . ' ] --- ' . $output; $output = '[ ' . date('Y-m-d H:i:s', time()) . ' ] --- ' . $output;
$formatter = new LineFormatter($output . "\r\n"); $formatter = new LineFormatter($output . "\r\n");
$stream->setFormatter($formatter); $stream->setFormatter($formatter);
$log->pushHandler($stream); $log->pushHandler($stream);
$log->pushHandler($fire); $log->pushHandler($fire);
$log->alert(''); $log->alert('');
} }
} }
if (!function_exists('http_to_server_url')) { if (!function_exists('http_to_server_url')) {
/** /**
* description:将前端的绝对路径转化为服务端相对路径 * description:将前端的绝对路径转化为服务端相对路径
* author: fuyunnan * author: fuyunnan
* @param string $path 需要转化的路径 * @param string $path 需要转化的路径
* @return string * @return string
* @throws * @throws
* Date: 2020/6/24 * Date: 2020/6/24
*/ */
function http_to_server_url($path) function http_to_server_url($path)
{ {
$path = ltrim(parse_url($path, PHP_URL_PATH), '/'); $path = ltrim(parse_url($path, PHP_URL_PATH), '/');
return 'public/' . $path; return 'public/' . $path;
} }
} }
if (!function_exists('empty_string_2_null')) { if (!function_exists('empty_string_2_null')) {
/** /**
* 空字符串转NULL * 空字符串转NULL
* @param array $arr * @param array $arr
* @return array * @return array
*/ */
function empty_string_2_null(array $arr) function empty_string_2_null(array $arr)
{ {
if (!empty($arr)) { if (!empty($arr)) {
foreach ($arr as $key => $value) { foreach ($arr as $key => $value) {
if (is_array($value)) { if (is_array($value)) {
$arr[$key] = empty_string_2_null($value); $arr[$key] = empty_string_2_null($value);
} else { } else {
if ($value === '') { if ($value === '') {
$arr[$key] = null; $arr[$key] = null;
} }
} }
} }
} }
return $arr; return $arr;
} }
} }
if (!function_exists('get_collection_values')) { if (!function_exists('get_collection_values')) {
/** /**
* 从集合中提取深层数据 * 从集合中提取深层数据
* @param mixed $collection 数据集合 * @param mixed $collection 数据集合
* @param string $key 集合中键 支持多层提取,例如"a.b.c" * @param string $key 集合中键 支持多层提取,例如"a.b.c"
* @return array | collection * @return array | collection
*/ */
function get_collection_values($collection, string $key) function get_collection_values($collection, string $key)
{ {
$values = []; $values = [];
if (!empty($collection) && (is_object($collection) || is_array($collection))) { if (!empty($collection) && (is_object($collection) || is_array($collection))) {
$itemKeys = explode(".", $key); $itemKeys = explode(".", $key);
$keyCount = count($itemKeys) - 1; $keyCount = count($itemKeys) - 1;
foreach ($collection as $value) { foreach ($collection as $value) {
foreach ($itemKeys as $k => $ik) { foreach ($itemKeys as $k => $ik) {
if (isset($value[$ik])) { if (isset($value[$ik])) {
$value = $value[$ik]; $value = $value[$ik];
if ($k == $keyCount) { if ($k == $keyCount) {
$values[] = $value; $values[] = $value;
} }
} else { } else {
if (is_array($value) || is_countable($collection)) { if (is_array($value) || is_countable($collection)) {
foreach ($value as $vv) { foreach ($value as $vv) {
if (isset($vv[$ik])) { if (isset($vv[$ik])) {
$values[] = $vv[$ik]; $values[] = $vv[$ik];
} }
} }
} }
break; break;
} }
} }
} }
} }
return $values; return $values;
} }
} }
if (!function_exists('put_collection_values')) { if (!function_exists('put_collection_values')) {
/** /**
* 对集合中设置深层数据 * 对集合中设置深层数据
* @param array | collection $collection 需要设置的数据集合 * @param array | collection $collection 需要设置的数据集合
* @param array | collection $valueList 需要设置值集合 * @param array | collection $valueList 需要设置值集合
* @param string $collectionKey 集合中键 支持多层提取,例如"user.info" * @param string $collectionKey 集合中键 支持多层提取,例如"user.info"
* @param string $collectionNewKey 数据集合的新键,例如"infomation",同名会覆盖 * @param string $collectionNewKey 数据集合的新键,例如"infomation",同名会覆盖
* @param string $valueKey $valueList中的值字段,例如"user_id" * @param string $valueKey $valueList中的值字段,例如"user_id"
* @return array | collection * @return array | collection
*/ */
function put_collection_values($collection, $valueList, string $collectionKey, string $collectionNewKey, $valueKey) function put_collection_values($collection, $valueList, string $collectionKey, string $collectionNewKey, $valueKey)
{ {
if (!empty($collection) && (is_object($collection) || is_array($collection))) { if (!empty($collection) && (is_object($collection) || is_array($collection))) {
$itemKeys = explode(".", $collectionKey); $itemKeys = explode(".", $collectionKey);
if (!empty($valueList)) { if (!empty($valueList)) {
if (!is_object($valueList)) { if (!is_object($valueList)) {
$valueList = collect($valueList); $valueList = collect($valueList);
} }
$valueList = $valueList->keyBy($valueKey); $valueList = $valueList->keyBy($valueKey);
} }
if (isset($collection[0])) { if (isset($collection[0])) {
foreach ($collection as $index => $value) { foreach ($collection as $index => $value) {
$collection[$index] = private_put_collection_values($value, $itemKeys, $valueList, $collectionNewKey); $collection[$index] = private_put_collection_values($value, $itemKeys, $valueList, $collectionNewKey);
} }
} else { } else {
private_put_collection_values($collection, $itemKeys, $valueList, $collectionNewKey); private_put_collection_values($collection, $itemKeys, $valueList, $collectionNewKey);
} }
} }
return $collection; return $collection;
} }
} }
if (!function_exists('private_put_collection_values')) { if (!function_exists('private_put_collection_values')) {
/** /**
* 对集合设置值,不对外公开 * 对集合设置值,不对外公开
* @param $collection * @param $collection
* @param $itemKeys * @param $itemKeys
* @param $valueList * @param $valueList
* @param $collectionNewKey * @param $collectionNewKey
* @return mixed * @return mixed
*/ */
function private_put_collection_values(&$collection, $itemKeys, $valueList, $collectionNewKey) function private_put_collection_values(&$collection, $itemKeys, $valueList, $collectionNewKey)
{ {
if (isset($collection[$itemKeys[0]])) { if (isset($collection[$itemKeys[0]])) {
if (count($itemKeys) != 1) { if (count($itemKeys) != 1) {
$t = $itemKeys[0]; $t = $itemKeys[0];
unset($itemKeys[0]); unset($itemKeys[0]);
$itemKeys = array_values($itemKeys); $itemKeys = array_values($itemKeys);
if (is_array($collection[$t]) || is_countable($collection[$t])) { if (is_array($collection[$t]) || is_countable($collection[$t])) {
foreach ($collection[$t] as $k => $v) { foreach ($collection[$t] as $k => $v) {
$collection[$t][$k] = private_put_collection_values($v, $itemKeys, $valueList, $collectionNewKey); $collection[$t][$k] = private_put_collection_values($v, $itemKeys, $valueList, $collectionNewKey);
} }
} else { } else {
$collection[$t] = private_put_collection_values($collection[$t], $itemKeys, $valueList, $collectionNewKey); $collection[$t] = private_put_collection_values($collection[$t], $itemKeys, $valueList, $collectionNewKey);
} }
} else { } else {
if (isset($valueList[$collection[$itemKeys[0]]])) { if (isset($valueList[$collection[$itemKeys[0]]])) {
$collection[$collectionNewKey] = $valueList[$collection[$itemKeys[0]]]; $collection[$collectionNewKey] = $valueList[$collection[$itemKeys[0]]];
} else { } else {
$collection[$collectionNewKey] = null; $collection[$collectionNewKey] = null;
} }
} }
} }
return $collection; return $collection;
} }
} }
if (!function_exists('human_time')) { if (!function_exists('human_time')) {
/** /**
* 计算时间 * 计算时间
* @param $time 时间戳 * @param $time 时间戳
* @return string * @return string
*/ */
function human_time($time) function human_time($time)
{ {
if (!is_numeric($time)) { if (!is_numeric($time)) {
$time = strtotime($time); $time = strtotime($time);
} }
$time = abs($time); $time = abs($time);
//计算天数 //计算天数
$days = intval($time / 86400); $days = intval($time / 86400);
if ($days != 0) { if ($days != 0) {
return $days . "天"; return $days . "天";
} }
//计算小时数 //计算小时数
$remain = $time % 86400; $remain = $time % 86400;
$hours = intval($remain / 3600); $hours = intval($remain / 3600);
if ($hours != 0) { if ($hours != 0) {
return $hours . "小时"; return $hours . "小时";
} }
//计算分钟数 //计算分钟数
$remain = $time % 3600; $remain = $time % 3600;
$mins = intval($remain / 60); $mins = intval($remain / 60);
if ($mins != 0) { if ($mins != 0) {
return $mins . "分钟"; return $mins . "分钟";
} }
//计算秒数 //计算秒数
$secs = $time % 60; $secs = $time % 60;
return $secs . "秒"; return $secs . "秒";
} }
} }
if (!function_exists('info')) { if (!function_exists('info')) {
/** /**
* 输出数据到控制台 * 输出数据到控制台
* @param mixed ...$arguments * @param mixed ...$arguments
*/ */
function info(...$arguments) function info(...$arguments)
{ {
var_dump(...$arguments); var_dump(...$arguments);
} }
} }
if (!function_exists('make_belong_relation_function')) { if (!function_exists('make_belong_relation_function')) {
/** /**
* 创建我属于关联关系的函数 * 创建我属于关联关系的函数
* @param string $relationName 关联关系的名字 * @param string $relationName 关联关系的名字
* @param array $mainModelColumns 使用关联关系的主表要筛选的列 * @param array $mainModelColumns 使用关联关系的主表要筛选的列
* @param array $relationColumns 关联关系的列 默认['id', 'name'] * @param array $relationColumns 关联关系的列 默认['id', 'name']
* @param string $mainModelRelationKey 主表和关联关系对应的字段 空的话为$relationName+"_id" * @param string $mainModelRelationKey 主表和关联关系对应的字段 空的话为$relationName+"_id"
* @param callable|null $callback 内嵌级联调用 * @param callable|null $callback 内嵌级联调用
* @return Closure 返回关联关系的匿名函数 * @return Closure 返回关联关系的匿名函数
*/ */
function make_belong_relation_function($relationName, array &$mainModelColumns, $relationColumns = ['id', 'name'], $mainModelRelationKey = "", callable $callback = null) function make_belong_relation_function($relationName, array &$mainModelColumns, $relationColumns = ['id', 'name'], $mainModelRelationKey = "", callable $callback = null)
{ {
$key = $mainModelRelationKey ? $mainModelRelationKey : $relationName . "_id"; $key = $mainModelRelationKey ? $mainModelRelationKey : $relationName . "_id";
if (!in_array($key, $mainModelColumns)) array_push($mainModelColumns, $key); if (!in_array($key, $mainModelColumns)) array_push($mainModelColumns, $key);
return make_has_relation_function($relationColumns, $callback); return make_has_relation_function($relationColumns, $callback);
} }
} }
if (!function_exists('make_has_relation_function')) { if (!function_exists('make_has_relation_function')) {
/** /**
* 创建我有关联关系的函数 * 创建我有关联关系的函数
* @param array $relationColumns 关联关系的列 默认['id', 'name'] * @param array $relationColumns 关联关系的列 默认['id', 'name']
* @param callable|null $callback 内嵌级联调用 * @param callable|null $callback 内嵌级联调用
* @return Closure 返回关联关系的匿名函数 * @return Closure 返回关联关系的匿名函数
* @return Closure * @return Closure
*/ */
function make_has_relation_function($relationColumns = ['id', 'name'], callable $callback = null) function make_has_relation_function($relationColumns = ['id', 'name'], callable $callback = null)
{ {
return function ($q) use ($relationColumns, $callback) { return function ($q) use ($relationColumns, $callback) {
$q->select($relationColumns); $q->select($relationColumns);
if (is_callable($callback)) { if (is_callable($callback)) {
$callback($q); $callback($q);
} }
}; };
} }
} }
if (!function_exists('int_to_chr')) { if (!function_exists('int_to_chr')) {
/** /**
* 数字转字母 (类似于Excel列标) * 数字转字母 (类似于Excel列标)
* @param mixed $index 索引值 * @param mixed $index 索引值
* @param int $start 字母起始值 * @param int $start 字母起始值
* @return string 返回字母 * @return string 返回字母
*/ */
function int_to_chr($index, $start = 65) function int_to_chr($index, $start = 65)
{ {
$str = ''; $str = '';
if (floor($index / 26) > 0) { if (floor($index / 26) > 0) {
$str .= int_to_chr(floor($index / 26) - 1); $str .= int_to_chr(floor($index / 26) - 1);
} }
return $str . chr($index % 26 + $start); return $str . chr($index % 26 + $start);
} }
} }
if (!function_exists('check_diff_val')) { if (!function_exists('check_diff_val')) {
/** /**
* 判断两个对象数组是否有不同的值 * 判断两个对象数组是否有不同的值
* 后者里有前者的key时,但value不一样,返回true * 后者里有前者的key时,但value不一样,返回true
* 后者里没有前者的key,或有key,但value一样时,返回false * 后者里没有前者的key,或有key,但value一样时,返回false
* @param array $list * @param array $list
* @param array $data * @param array $data
* @return bool * @return bool
*/ */
function check_diff_val(array $list, array $data) function check_diff_val(array $list, array $data)
{ {
foreach ($list as $key => $val) { foreach ($list as $key => $val) {
if (isset($data[$key]) && $data[$key]) { if (isset($data[$key]) && $data[$key]) {
if (is_array($val)) { if (is_array($val)) {
if (check_diff_val($val, $data[$key])) { if (check_diff_val($val, $data[$key])) {
return true; return true;
} }
} else { } else {
if ($list[$key] != $data[$key]) { if ($list[$key] != $data[$key]) {
return true; return true;
} }
} }
} }
} }
return false; return false;
} }
} }
if (!function_exists('get_diff_val')) { if (!function_exists('get_diff_val')) {
/** /**
* 获取两个数组中key相同,value不同的数据 * 获取两个数组中key相同,value不同的数据
* 返回后者的数据 * 返回后者的数据
* @param array $list1 * @param array $list1
* @param array $list2 * @param array $list2
* @param array $excludeKey 排除的key数组 * @param array $excludeKey 排除的key数组
* @return array * @return array
* @author Zero * @author Zero
*/ */
function get_diff_val(array $list1, array $list2, array $excludeKey = []) function get_diff_val(array $list1, array $list2, array $excludeKey = [])
{ {
$diff = []; $diff = [];
foreach ($list1 as $key => $val) { foreach ($list1 as $key => $val) {
if (!in_array($key, $excludeKey)) { if (!in_array($key, $excludeKey)) {
if (isset($list2[$key]) && $list2[$key] != '') { if (isset($list2[$key]) && $list2[$key] != '') {
if (is_array($val)) { if (is_array($val)) {
$temp = get_diff_val($val, $list2[$key], $excludeKey); $temp = get_diff_val($val, $list2[$key], $excludeKey);
!empty($temp) && $diff[$key] = $temp; !empty($temp) && $diff[$key] = $temp;
} else { } else {
if ($list1[$key] != $list2[$key]) { if ($list1[$key] != $list2[$key]) {
$diff[$key] = $list2[$key]; $diff[$key] = $list2[$key];
} }
} }
} }
} }
} }
return $diff; return $diff;
} }
} }
if (!function_exists('to_camel_case')) { if (!function_exists('to_camel_case')) {
/** /**
* 下划线命名转驼峰命名 * 下划线命名转驼峰命名
* 例:demo_function : demoFunction * 例:demo_function : demoFunction
* @param $dirSep 分隔符 * @param $dirSep 分隔符
* @param $str * @param $str
* @return mixed|string * @return mixed|string
*/ */
function to_camel_case($dirSep, $str) function to_camel_case($dirSep, $str)
{ {
$array = explode($dirSep, $str); $array = explode($dirSep, $str);
$result = $array[0]; $result = $array[0];
$len = count($array); $len = count($array);
if ($len > 1) { if ($len > 1) {
for ($i = 1; $i < $len; $i++) { for ($i = 1; $i < $len; $i++) {
$result .= ucfirst($array[$i]); $result .= ucfirst($array[$i]);
} }
} }
return $result; return $result;
} }
} }
if (!function_exists('mb_trim')) { if (!function_exists('mb_trim')) {
/** /**
* 去除两边带全角空格的字符串 * 去除两边带全角空格的字符串
* @param $str * @param $str
* @return string * @return string
* @author zero * @author zero
*/ */
function mb_trim($str) function mb_trim($str)
{ {
mb_regex_encoding('utf-8'); mb_regex_encoding('utf-8');
$str = mb_ereg_replace(' ', '', $str); $str = mb_ereg_replace(' ', '', $str);
return trim($str); return trim($str);
} }
} }
if (!function_exists('str_replace_first')) { if (!function_exists('str_replace_first')) {
/** /**
* 用替换字符串替换第一个出现的搜索字符串 * 用替换字符串替换第一个出现的搜索字符串
* @param mixed $search 搜索字符串 * @param mixed $search 搜索字符串
* @param mixed $replace 替换字符串 * @param mixed $replace 替换字符串
* @param mixed $subject 被替换字符串 * @param mixed $subject 被替换字符串
* @return string * @return string
* @author zero * @author zero
*/ */
function str_replace_first($search, $replace, $subject) function str_replace_first($search, $replace, $subject)
{ {
if (($position = strpos($subject, $search)) !== false) { if (($position = strpos($subject, $search)) !== false) {
$replaceLen = strlen($search); $replaceLen = strlen($search);
$subject = substr_replace($subject, $replace, $position, $replaceLen); $subject = substr_replace($subject, $replace, $position, $replaceLen);
} }
return $subject; return $subject;
} }
} }
if (!function_exists('create_file_dir')) { if (!function_exists('create_file_dir')) {
/** /**
* 检查当前目录是否存在 不存在就创建一个目录 * 检查当前目录是否存在 不存在就创建一个目录
* @param mixed $dir 文件目录 * @param mixed $dir 文件目录
* @return bool * @return bool
* @author zero * @author zero
*/ */
function create_file_dir($dir) function create_file_dir($dir)
{ {
return !is_dir($dir) && mkdir($dir, 0777, true); return !is_dir($dir) && mkdir($dir, 0777, true);
} }
} }
if (!function_exists('get_images_url')) { if (!function_exists('get_images_url')) {
/** /**
* 富文本获取图片信息 * 富文本获取图片信息
* @param $str * @param $str
* @return mixed * @return mixed
*/ */
function get_images_url($str) function get_images_url($str)
{ {
preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i', $str, $match); preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i', $str, $match);
return $match; return $match;
} }
} }
if (!function_exists('download_file')) { if (!function_exists('download_file')) {
/** /**
* 下载远程文件 * 下载远程文件
* @param $url 远程文件路径 * @param $url 远程文件路径
* @param null $path 系统保存路径 * @param null $path 系统保存路径
* @return string * @return string
*/ */
function download_file($url, $path = null) function download_file($url, $path = null)
{ {
$filename = trim(pathinfo($url, PATHINFO_FILENAME)); $filename = trim(pathinfo($url, PATHINFO_FILENAME));
$ext = strtolower(pathinfo($url, PATHINFO_EXTENSION)); $ext = strtolower(pathinfo($url, PATHINFO_EXTENSION));
$filename = "$filename.$ext"; $filename = "$filename.$ext";
$root = config('server.settings.document_root', BASE_PATH . '/public'); $root = config('server.settings.document_root', BASE_PATH . '/public');
$path = $path ? $path : '/download/files'; $path = $path ? $path : '/download/files';
$savePath = $root . $path; $savePath = $root . $path;
if (!is_dir($savePath)) { if (!is_dir($savePath)) {
// 判断路径是否存在,不存在,则创建 // 判断路径是否存在,不存在,则创建
mkdir($savePath, 0777, true); mkdir($savePath, 0777, true);
} }
$filePath = $savePath . '/' . $filename; $filePath = $savePath . '/' . $filename;
if (!file_exists($filePath)) { if (!file_exists($filePath)) {
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$file = curl_exec($ch); $file = curl_exec($ch);
curl_close($ch); curl_close($ch);
$resource = fopen($filePath, 'a'); $resource = fopen($filePath, 'a');
fwrite($resource, $file); fwrite($resource, $file);
fclose($resource); fclose($resource);
} }
return $path . '/' . $filename;; return $path . '/' . $filename;;
} }
} }
if (!function_exists('download_file_stream')) { if (!function_exists('download_file_stream')) {
/**文件流保存到本地 /**文件流保存到本地
* @param $fileStream 文件流 * @param $fileStream 文件流
* @param null $path 保存路径 * @param null $path 保存路径
* @return string * @return string
*/ */
function download_file_stream($fileStream, $path = null) function download_file_stream($fileStream, $path = null)
{ {
$root = config('server.settings.document_root', BASE_PATH . '/public'); $root = config('server.settings.document_root', BASE_PATH . '/public');
$path = $path ? $path : '/download/files'; $path = $path ? $path : '/download/files';
$savePath = $root . $path; $savePath = $root . $path;
if (!is_dir($savePath)) { if (!is_dir($savePath)) {
// 判断路径是否存在,不存在,则创建 // 判断路径是否存在,不存在,则创建
mkdir($savePath, 0777, true); mkdir($savePath, 0777, true);
} }
$fileName = '/' . date('YmdHis') . 'track' . '.pdf'; $fileName = '/' . date('YmdHis') . 'track' . '.pdf';
file_put_contents($savePath . $fileName, base64_decode($fileStream), 1); file_put_contents($savePath . $fileName, base64_decode($fileStream), 1);
return $path . $fileName; return $path . $fileName;
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment