You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

666 lines
28 KiB

<?php
namespace app\service\task;
use app\model\Festivals;
use app\model\Goods;
use app\model\GoodsDetail;
use app\model\GoodsSource;
use app\model\OperationLog;
use app\model\Order;
use app\model\OrderGoodsDetail;
use app\model\User;
use app\service\BaseService;
use app\service\pay\PayService;
use fast\Http;
use http\Exception;
use think\Validate;
class GoodsService extends BaseService
{
protected $sourceTypeArr = [
"图书" => 1,
"期刊" => 2,
"报纸" => 3,
"音像" => 4,
"音频" => 5,
"视频" => 6,
"其他文献" => 7,
"图片" => 8,
"文化产品" => 9,
];
public function __construct()
{
parent::__construct();
$this->http = new Http();
$this->redis = new \Redis();
$this->redis->connect('127.0.0.1', 6379);
}
public function getApiGoods(){
$count = 0;
// 通过委托系统查询委托数据信息
//todo 请求获取委托信息接口 接口1.1
$path = env("app.entrust_url") . "/consign/exchange/v1/selectEntrustSource/exchange";
$sign = parent::createSign("entrust");
$headers = array(
CURLOPT_HTTPHEADER => array(
"entrust_token:{$sign}"
)
);
$result = $this->http::get($path, [], $headers);
if($result['code'] != 200){
// throw new \think\Exception($result['msg'], 400);
return $count;
}
$result = json_decode($result['data'], true);
if($result['resultCode'] != "00000000"){
// throw new \think\Exception($result['resultMsg'], 400);
return $count;
}
$goods = $result['data'];
$this->goodslog->info("获取委托数据", $goods);
$source_path = env("app.entrust_url") . "/consign/exchange/v1/selectEntrustDetails";
foreach($goods as $k => $v){
// if($v['isliCode'] != "010007-00000000085100000001-1"){
// continue;
// }
// var_dump($v);die;
// return $v;
if(!isset($v['targetData']) || !isset($v['sourceData'])){
continue;
}
// if($v['targetData']['identifier'] == "999998-0000000001234567890-2"){
// continue;
// }
// if(!$this->checkUser($v['targetData']['identifier'])){
// continue;
// }
if(!isset($v['sourceData']['collectionType'])){
continue;
}
if(empty($v['sourceData']['identifiers'])) {
continue;
}
if(empty($v['sourceData']['identifier'])) {
continue;
}
if($v['status'] == 6 || $v['status'] == 7){
continue;
}
// $contractual_period_one = $this->getOldPeriod($v['sourceData']['contractualPeriod']);
// $contractual_period_two = $this->getNewPeriod($v['sourceData']['contractualPeriod']);
// if($contractual_period_one == 0 && $contractual_period_two == 0){
// var_dump($v);die;
// }
// continue;
// if($v['isliCode'] != "010007-00000000050100000001-5"){
// continue;
// }
// 获取委托数据资源
//todo 请求获取委托信息资源详情接口 接口1.2
$res = $this->http::get($source_path . "/{$v['sourceData']['identifiers']}", [], $headers);
$this->goodslog->info("获取{$v['sourceData']['identifiers']}委托资源详情", $goods);
if($res['code'] != 200){
// throw new \think\Exception($res['msg'], 400);
continue;
}
$res = json_decode($res['data'], true);
if($res['resultCode'] != "00000000"){
// throw new \think\Exception($res['resultMsg'], 400);
continue;
}
$res = $res['data'];
$insert = 1;
if(Goods::where('goods_islicode', $v['sourceData']['identifier'])->value('id')){
continue;
// $insert = 0;
// GoodsSource::where('goods_isli_code', $v['isliCode'])->where('is_deleted', 0)->update(['is_deleted' => 1]);
}
$this->insertGoodsSource($res, $v['sourceData']['identifier']); // 添加商品资源详情
$goods_detail_id = $this->insertGoodsDetail($v, $res); // 添加商品明细
$status = 0;
if($v['status'] == 1 || $v['status'] == 4 || $v['status'] == 5){
$status = 1;
}elseif($v['status'] == 2){
$status = 2;
}else{
$status = 4;
}
$contractual_period = $this->getOldPeriod($v['sourceData']['contractualPeriod']);
$contractualPeriodStart = $v['sourceData']['contractualPeriodStart'];
$contractualPeriodEnd = $v['sourceData']['contractualPeriodEnd'];
if(!empty($contractualPeriodStart) && preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $contractualPeriodStart)){
$contractualPeriodStart .= date(' H:i:s');
}
if(!empty($contractualPeriodEnd) && preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $contractualPeriodEnd)){
$contractualPeriodEnd .= " 23:59:59";
}
if($contractual_period){
GoodsDetail::where('id', $goods_detail_id)->update(['contractual_period' => $contractual_period]);
$status = 2;
$old_status = 1;
}else{
$contractual_period = $this->getNewPeriod($v['sourceData']['contractualPeriod']);
GoodsDetail::where('id', $goods_detail_id)->update(['contractual_period' => $contractual_period]);
if($contractual_period == 2){
$day = $v['sourceData']['contractualCycle'];
$time = $this->getEndDate($contractualPeriodStart, $day);
$contractualPeriodEnd = date("Y-m-d 23:59:59", $time);
}elseif($contractual_period == 0){
$status = 2;
}
$old_status = 0;
}
if(strtotime($contractualPeriodStart) > time() && $status == 1){
$status = 2;
}
$goods_data = [
"goods_detail_id" => $goods_detail_id,
"contract_status" => $v['sourceData']['contractStatus'],
"contractual_start_time" => $contractualPeriodStart,
"contractualtime_end_time" => $contractualPeriodEnd,
"goods_status" => $status,
"old_status" => $old_status,
"entrust_status" => $v['status']
];
if($insert){
$goods_data["user_islicode"] = $v['targetData']['identifier'];
$goods_data["username"] = $v['targetData']['titleName'];
$goods_data['islicode'] = $v['isliCode'];
$goods_data["goods_islicode"] = $v['sourceData']['identifier'];
$flag = (new Goods())->insertGetId($goods_data);
if($flag){
// $this->redis->lPush($goods_data['goods_islicode'] . "_count", 1);
Goods::where('id', $flag)->update(['recommend_sort' => $flag]);
$operation_log = [
"type" => "goods",
"log_id" => $flag,
"message" => date('Y-m-d H:i:s')." 发布标的成功",
];
(new OperationLog())->insert($operation_log);
}else{
// throw new \think\Exception("添加失败", 400);
continue;
}
}else{
$flag = (new Goods())->where('goods_islicode', $v['sourceData']['identifier'])->update($goods_data);
if($flag){
if($this->redis->lLen($v['isliCode'] . "_count") <= 0){
// $this->redis->lPush($v['isliCode'] . "_count", 1);
}
}else{
// throw new \think\Exception("添加失败", 400);
continue;
}
}
$count++;
}
return $count;
}
public function goodsPast(){
$goods = Goods::where('goods_status', '1')->select()->toArray();
foreach($goods as $val){
if(empty($val['contractualtime_end_time'])){
continue;
}
$contractual_period = GoodsDetail::where('id', $val['goods_detail_id'])->value('contractual_period');
if($contractual_period != 2 && $contractual_period != 3){
continue;
}
if(strtotime($val['contractualtime_end_time']) <= time()){
$this->log->info("委托时间到期", "{$val['goods_islicode']}委托时间{$val['contractualtime_end_time']}已到期");
Goods::where('id', $val['id'])->update(['goods_status' => 4]);
//todo 请求交易所撤销委托接口 接口1.4
$url = env("app.entrust_url") . "/consign/exchange/v1/exchangeRevokeEntrust";
$sign = parent::createSign("entrust");
$headers = array(
CURLOPT_HTTPHEADER => array(
"entrust_token:{$sign}"
)
);
$post = [
"isliCode" => $val['islicode'],
"status" => 1,
"revokeReason" => "委托周期结束"
];
$this->goodslog->info("{$val['islicode']}委托时间到期", $post);
Http::get($url, $post, $headers);
$operation_log = [
"type" => "goods",
"log_id" => $val['id'],
"message" => date('Y-m-d H:i:s')." 委托标的过期失效!",
];
(new OperationLog())->insert($operation_log);
}
}
}
public function goodsDatePutaway(){
$goods = Goods::where('old_status', 0)->whereIn('entrust_status', '1,4,5')->where('goods_status', 2)->where('apply_out', 0)->select()->toArray();
foreach($goods as $val){
if(empty($val['contractualtime_end_time']) || empty($val['contractual_start_time'])){
continue;
}
$goods_detail = GoodsDetail::where('id', $val['goods_detail_id'])->find();
if($goods_detail->goods_entrust == 1 && $goods_detail->stock == 0){
continue;
}
if(strtotime($val['contractualtime_end_time']) <= time()){
continue;
}
if(strtotime($val['contractual_start_time']) <= time()){
Goods::where('id', $val['id'])->update(['goods_status' => 1]);
}
}
}
public function checkUser($user_isli){
$user = User::where('user_isli', $user_isli)->find();
if($user){
return true;
}
//todo 请求根据账号ID查询用户信息接口 接口3.1
$path = env('app.real_url') . "/users/usermgt/v1/user-info/{$user_isli}";
$sign = parent::createSign("user_real");
$headers = array(
CURLOPT_HTTPHEADER => array(
"api_token:{$sign}",
// "Content-Type: application/json"
)
);
$result = Http::get($path, [], $headers);
if($result['code'] != 200){
throw new \think\Exception($result['msg'], 400);
}
$result = json_decode($result['data'], true);
if($result['resultCode'] != "00000000"){
throw new \think\Exception($result['resultMsg'], 400);
}
$userinfo = $result['data'];
if(!isset($userinfo['legalsCellPhone'])){
// var_dump($userinfo);die;
}
$insert = [];
if($userinfo['userType'] == "机构"){
$insert = [
"agency_type" => 2,
"attest_status" => $userinfo['state'] + 1,
"user_isli" => $userinfo['islicode'],
"username" => $userinfo['name'],
"institution_code" => $userinfo['uscc'],
"legals_name" => $userinfo['legalsName'],
"legals_type" => $userinfo['legalsType'],
"legals_idnum" => $userinfo['legalsIdnum'],
"legals_phone" => (isset($userinfo['legalsCellPhone']) ? $userinfo['legalsCellPhone'] : ''),
"bank_account" => $userinfo['publicAccount'],
"bank_card_type" => $userinfo['bankCardType'],
"bank_name" => $userinfo['bankName'],
"bank_type" => $userinfo['bankType'],
"bank_username" => $userinfo['bankAccountName'],
"bank_userid" => $userinfo['certIdnum'],
"bank_userphone" => $userinfo['bankCellPhone'],
"bank_address" => $userinfo['bankAddress'],
];
}else{
$insert = [
"agency_type" => 1,
"attest_status" => $userinfo['state'] + 1,
"user_isli" => $userinfo['islicode'],
"username" => $userinfo['Name'],
"cert_type" => $userinfo['certType'],
"idNumber" => $userinfo['idNumber'],
"cell_phone" => $userinfo['cellPhone'],
"bank_account" => $userinfo['publicAccount'],
"bank_card_type" => $userinfo['bankCardType'],
"bank_name" => $userinfo['bankName'],
"bank_username" => $userinfo['bankAccountName'],
"bank_userid" => $userinfo['certIdnum'],
"bank_userphone" => $userinfo['bankCellPhone'],
"bank_address" => $userinfo['bankAddress'],
];
}
$insert['registertime'] = date('Y-m-d H:i:s');
$insert['attesttime'] = date('Y-m-d H:i:s');
(new User())->insert($insert);
return true;
}
public function getRevocationGoods(){
//todo 请求获取撤销委托信息 接口 接口1.3
$path = env("app.entrust_url") . "/consign/exchange/v1/selectRevokeEntrust/exchange";
$this->log->info("获取撤销ISLI地址", $path);
$sign = parent::createSign("entrust");
$headers = array(
CURLOPT_HTTPHEADER => array(
"entrust_token:{$sign}"
)
);
$result = $this->http::get($path, [], $headers);
if($result['code'] != 200){
throw new \think\Exception($result['msg'], 400);
}
$result = json_decode($result['data'], true);
if($result['resultCode'] != "00000000"){
throw new \think\Exception($result['resultMsg'], 400);
}
$result = $result['data'];
$this->goodslog->info("获取撤销委托数据", $result);
foreach($result as $key => $val){
if(Goods::where('islicode', $val['isliCode'])->where('goods_status', 1)->update(['goods_status' => 2, 'apply_out' => 1])){
$this->orderRevocation($val['isliCode']);
$goods_id = Goods::where('islicode', $val['isliCode'])->where('is_deleted', 0)->value('id');
$operation_log = [
"type" => "goods",
"log_id" => $goods_id,
"message" => date('Y-m-d H:i:s')." 发布投送系统撤销委托",
];
(new OperationLog())->insert($operation_log);
}
}
}
public function getRevocationResult(){
//todo 请求查询撤销审核数据(交易所/委托)接口 接口1.5
$path = env("app.entrust_url") . "/consign/exchange/v1/selectVerifyStatus";
$sign = parent::createSign("entrust");
$headers = array(
CURLOPT_HTTPHEADER => array(
"entrust_token:{$sign}"
)
);
$result = $this->http::get($path, [], $headers);
if($result['code'] != 200){
throw new \think\Exception($result['msg'], 400);
}
$result = json_decode($result['data'], true);
if($result['resultCode'] != "00000000"){
throw new \think\Exception($result['resultMsg'], 400);
}
$result = $result['data'];
$this->goodslog->info("获取撤销委托数据结果", $result);
foreach($result as $key => $val){
if($val['revokeStatus'] != 2){
// continue;
}
if($val['verifyStatus'] == 0){
continue;
}
if($val['verifyStatus'] == 1){
if(Goods::where('islicode', $val['isliCode'])->where('apply_out', 1)->update(['goods_status' => 2])){
$this->orderRevocation($val['isliCode']);
$operation_log = [
"type" => "goods",
"log_id" => Goods::where('islicode', $val['isliCode'])->value('id'),
"message" => date('Y-m-d H:i:s') . " 申请撤销委托审核通过"
];
(new OperationLog())->insert($operation_log);
}else{
if(Goods::where('islicode', $val['isliCode'])->where('goods_status', 'in', '1,5')->update(['goods_status' => 2, 'apply_out' => 1])){
$this->orderRevocation($val['isliCode']);
$operation_log = [
"type" => "goods",
"log_id" => Goods::where('islicode', $val['isliCode'])->value('id'),
"message" => date('Y-m-d H:i:s') . " 委托系统撤销委托"
];
(new OperationLog())->insert($operation_log);
}
}
}else{
if(Goods::where('islicode', $val['isliCode'])->where('apply_out', 1)->update(['apply_out' => 0])){
$operation_log = [
"type" => "goods",
"log_id" => Goods::where('islicode', $val['isliCode'])->value('id'),
"message" => date('Y-m-d H:i:s') . " 申请撤销委托审核不通过"
];
(new OperationLog())->insert($operation_log);
}
}
}
}
public function orderRevocation($islicode){
$order_goods_detail = OrderGoodsDetail::alias('detail')
->join('order order', 'order.batchcode = detail.batchcode')
->where('detail.islicode', $islicode)
->where('order.status', 1)
->where('detail.is_deleted', 0)
->field('detail.batchcode')
->select()->toArray();
foreach($order_goods_detail as $val){
if(OrderGoodsDetail::where('batchcode', $val['batchcode'])->where('is_deleted', 0)->count() > 1){
$total_service_charge = OrderGoodsDetail::where('batchcode', $val['batchcode'])->where('islicode', '<>', $islicode)->where('is_deleted', 0)->sum('service_charge');
$total_money = OrderGoodsDetail::where('batchcode', $val['batchcode'])->where('islicode', '<>', $islicode)->where('is_deleted', 0)->sum('money');
Order::where('batchcode', $val['batchcode'])->update(['total_service_charge' => $total_service_charge, 'total_money' => $total_money]);
}else{
Order::where('batchcode', $val['batchcode'])->update(['status' => 5]);
}
OrderGoodsDetail::where('batchcode', $val['batchcode'])->where('islicode', $islicode)->update(['is_deleted' => 1]);
if(Order::where('batchcode', $val['batchcode'])->value('total_money') <= 0){
Order::where('batchcode', $val['batchcode'])->update(['status' => 2, 'pay_status' => 2, 'paymenttime' => date('Y-m-d H:i:s')]);
$pay_service = new PayService();
$pay_service->payFinishOperate($val['batchcode']);
}
}
}
public function insertGoodsSource($res, $islicode){
foreach($res as $key => $val){
// $source_type = $this->getSourceType($val['sourceType'] ?? '');
$source = [
"servicecode" => isset($val['serviceCode']) ? $val['serviceCode'] : "",
"linkcode" => isset($val['linkCode']) ? $val['linkCode'] : "",
"publisherid" => isset($val['publisherId']) ? $val['publisherId'] : "",
"registrant" => isset($val['register']) ? $val['register'] : "",
"resolution_url" => isset($val['resolutionUrl']) ? $val['resolutionUrl'] : "",
"source_type" => isset($val['sourceType']) ? $val['sourceType'] : "",
"source_name_type" => isset($val['sourceNameType']) ? $val['sourceNameType'] : "",
"source_name" => isset($val['sourceName']) ? $val['sourceName'] : "",
"sourceIdentify" => isset($val['sourceIdentify']) ? $val['sourceIdentify'] : "",
"source_fragment" => isset($val['sourceFragment']) ? $val['sourceFragment'] : "",
"target_name" => isset($val['targetName']) ? $val['targetName'] : "",
"target_name_type" => isset($val['targetNameType']) ? $val['targetNameType'] : "",
"targetIdentify" => isset($val['targetIdentify']) ? $val['targetIdentify'] : "",
"target_fragment" => isset($val['targetFragment']) ? $val['targetFragment'] : "",
"targetFormat" => isset($val['targetFormat']) ? $val['targetFormat'] : "",
"source_data" => isset($val['sourceData']) ? $val['sourceData'] : "",
"target_data" => isset($val['targetData']) ? $val['targetData'] : "",
"metadataXml" => isset($val['metadataXml']) ? $val['metadataXml'] : "",
"cancellation_reason" => isset($val['cancellationReason']) ? $val['cancellationReason'] : "",
"allocationtime" => isset($val['allocationDate']) ? $val['allocationDate'] : "",
"datatype" => $val['dataType'],
];
if(isset($val['cancellationDate'])){
$source['cancellationtime'] = $val['cancellationDate'];
}
$source['goods_isli_code'] = $islicode;
(new GoodsSource())->insert($source);
}
}
public function insertGoodsDetail($data, $source){
$price = (float)str_replace("RMB ", "", $data['sourceData']['price']);
$goods_detail = [
"goods_name" => (isset($data['sourceData']['titleName']) ? $data['sourceData']['titleName'] : ""),
"goods_image" => (isset($data['sourceData']['cover']) ? $data['sourceData']['cover'] : ""),
"price" => $price,
"goods_type" => ($data['sourceData']['collectionType'] == "文化资源数据" ? 1 : 2),
"charges_type" => ($price <= 0 ? 1 : 2),
"goods_islicode" => $data['sourceData']['identifier'],
"contractual_period" => 0,
"sourcedata_islicode" => $data['sourceData']['isliCode'],
"earnest_money" => 0,
"transaction_class" => ($data['sourceData']['transactionKind'] == "权属" ? 1 : 2),
"contract" => isset($data['sourceData']['description']) ? $data['sourceData']['description'] : "",
"otherIdentifiers" => isset($data['sourceData']['otherIdentifiers']) ? $data['sourceData']['otherIdentifiers'] : "",
"data_json" => json_encode($data),
"source_json" => json_encode($source)
];
// if($goods_detail['contractual_period'] == 3){
// // 周期
// $goods_detail['entrust_month'] = 1;
// }
if($goods_detail['transaction_class'] == 1){
// 权属
$goods_detail['identifier'] = isset($data['sourceData']['identifier']) ? $data['sourceData']['identifier'] : "";
$goods_detail['identifiers'] = isset($data['sourceData']['identifiers']) ? $data['sourceData']['identifiers'] : "";
$goods_detail["goods_ownership_str"] = isset($data['sourceData']['rights']) ? $data['sourceData']['rights'] : "";
$goods_detail["goods_entrust"] = ($data['sourceData']['transactionType'] == "授权" ? 2 : 1);
if($goods_detail["goods_entrust"] == 2){
$goods_detail['stock'] = -1;
}else{
$goods_detail['stock'] = 1;
}
}else{
// 商品
$goods_detail['identifier'] = isset($data['sourceData']['identifier']) ? $data['sourceData']['identifier'] : "";
$goods_detail["goods_entrust"] = ($data['sourceData']['transactionType'] == "租赁" ? 3 : 4);
$goods_detail['classification'] = isset($data['sourceData']['classification']) ? $data['sourceData']['classification'] : "";
$goods_detail['stock'] = 1;
// $this->redis->lPush($data['isliCode'] . "_stock", 1);
}
$goods_detail_id = (new GoodsDetail())->insertGetId($goods_detail);
return $goods_detail_id;
}
public function getOldPeriod($contractual_period){
switch ($contractual_period){
case "永久":
return 1;
case "单次":
return 2;
case "周期":
return 3;
default:
return 0;
}
return 0;
}
public function getNewPeriod($contractual_period){
switch ($contractual_period){
case "永久性委托":
return 1;
case "一次性委托":
return 2;
case "阶段性委托":
return 3;
default:
return 0;
}
return 0;
}
public function getEndDate($starttime, $day){
// 法定节假日数组
$festivals = Festivals::where('year', date('Y-m-d'))->field('date')->select()->toArray();
$festivals = array_column($festivals, 'date');
$time = strtotime("+1 day", strtotime($starttime));
while(true){
if(date('N', $time) > 5){ // 周末
$time = strtotime("+1 day", $time);
continue;
}
if(in_array( date('Y-m-d', $time), $festivals)){ // 法定节假日
$time = strtotime("+1 day", $time);
continue;
}
$day--;
if($day <= 0){
break;
}
$time = strtotime("+1 day", $time);
}
return $time;
}
public function getSourceType($str){
$source_type = 0;
foreach($this->sourceTypeArr as $key => $val){
if(strpos($str, $key) !== false){
$source_type = $val;
break;
}
}
return $source_type;
}
public function goodsJoinField(){
$goods_detail = GoodsDetail::where('is_deleted', 0)->where('is_join', 0)->field('id,data_json,source_json')->select()->toArray();
foreach($goods_detail as $value){
$goods = json_decode($value['data_json'], true);
$source = json_decode($value['source_json'], true);
$str = $this->joinField($goods, $source);
// preg_match_all("/[\x{4e00}-\x{9fa5}]+/u", $str, $res);
preg_match_all("/[\x{4e00}-\x{9fa5}a-zA-Z]+/u", $str, $res);
$res = implode('', $res[0]);
GoodsDetail::where('id', $value['id'])->update(['join_field' => $res, 'is_join' => 1]);
}
}
public function joinField(array $goods = [], array $source = []){
// todo 将委托数据字段拼接字符串
$str = "";
if(isset($goods['sourceData'])){
$source_data = $goods['sourceData'];
$str .= implode('', $source_data);
$goods['sourceData'] = null;
}
if(isset($goods['targetData'])){
$target_data = $goods['targetData'];
$str .= implode('', $target_data);
$goods['targetData'] = null;
}
$str .= implode('', $goods);
foreach($source as &$value){
if(isset($value['sourceData'])){
$str .= implode('', json_decode($value['sourceData'], true));
$value['sourceData'] = null;
}
if(isset($value['targetData'])){
$str .= implode('', json_decode($value['targetData'], true));
$value['targetData'] = null;
}
$str .= implode('', $value);
}
return $str;
}
}