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.

1748 lines
83 KiB

<?php
namespace app\service\order;
use app\model\AccountRatioDetail;
use app\model\AccountRatioSetting;
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\OrderGoodsSource;
use app\model\OrderUser;
use app\model\Ticket;
use app\model\User;
use app\model\UserAccountBill;
use app\Request;
use app\service\BaseService;
use app\service\pay\ApiHelperoneService;
use app\service\pay\PayService;
use app\service\pay\security;
use app\service\pay\SeparateAccountService;
use app\service\user\UserService;
use fast\Http;
class OrderService extends BaseService
{
protected $redis = null;
public function __construct()
{
parent::__construct();
$this->redis = new \Redis();
$this->redis->connect('127.0.0.1', 6379);
// $this->redis->auth('123456');
}
protected function createOrderBatchcode(){
return time() . substr(rand(1000000, 9999999), 1);
}
protected function getOrderCode(){
return "TEST" . date('YmdHis');
}
public function orderShut($batchcode){
$order = Order::where('batchcode', $batchcode)->find();
if(!$order){
throw new \think\Exception('未查询到该订单', 400);
}
$order_detail = OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)->field("goods_islicode")->select()->toArray();
foreach($order_detail as $value){
$goods_detail_id = Goods::where('goods_islicode', $value['goods_islicode'])->value('goods_detail_id');
if(!$goods_detail_id){
continue;
}
$goods_detail = GoodsDetail::where('id', $goods_detail_id)->where('is_deleted', 0)->find();
if(!$goods_detail){
continue;
}
if($goods_detail->goods_entrust == 1){
$goods_detail->stock = 1;
$goods_detail->save();
Goods::where('goods_islicode', $value['goods_islicode'])->update(['goods_status' => 1]);
}
}
$order->status = 5;
$order->shuttime = date('Y-m-d H:i:s');
return $order->save();
}
public function list($batchcode, $entrust_name, $buy_name, $goods_name, $order_type, $entrust_type, $transaction_status, $createtime, $goods_isli, $charges_type, $page, $limit){
$where = [];
if(!empty($batchcode)){
$where['order.batchcode'] = $batchcode;
}
if(!empty($entrust_name)){
// $where['entrust_name'] = $entrust_name;
$entrust_isli_ids = OrderUser::whereLike('name', "%".$entrust_name."%", "or")->whereLike("islicode", "%{$entrust_name}%", "or")->field('islicode')->select()->toArray();
if($entrust_isli_ids){
$entrust_isli_ids = implode(',', array_column($entrust_isli_ids, 'islicode'));
}else{
$entrust_isli_ids = -1;
}
}else{
$entrust_isli_ids = 0;
}
if(!empty($buy_name)){
$buy_isli_arr = OrderUser::whereLike('name', "%".$buy_name."%", "or")->whereLike("islicode", "%{$buy_name}%", "or")->field('islicode,batchcode')->select()->toArray();
if($buy_isli_arr){
$buy_isli_ids['batchcode'] = implode(',', array_column($buy_isli_arr, 'batchcode'));
$buy_isli_ids['islicode'] = implode(',', array_column($buy_isli_arr, 'islicode'));
}else{
$buy_isli_ids = -1;
}
}else{
$buy_isli_ids = 0;
}
if(!empty($order_type)){
$where['order.type'] = $order_type;
}
if(!empty($transaction_status)){
$where['order.status'] = $transaction_status;
}
if(!empty($createtime)){
$where['createtime'] = $createtime;
}
if($buy_isli_ids){
$where['buyisli'] = $buy_isli_ids;
}
//if(!empty($entrust_isli_ids) || !empty($goods_name) || !empty($entrust_type) || !empty($goods_isli) || !empty($charges_type)){
$batchcode_ids = OrderGoodsDetail::where(function ($query) use($entrust_isli_ids, $goods_name, $entrust_type, $goods_isli, $charges_type){
if($entrust_isli_ids){
$query->whereIn('entrust_islicode', $entrust_isli_ids);
}
if($goods_name){
$query->whereLike('goods_name', "%".$goods_name."%", "or")->whereLike("goods_islicode", "%{$goods_name}%", "or");
}
if($entrust_type){
$query->where('goods_entrust', $entrust_type);
}
if($goods_isli){
$query->where('goods_islicode', $goods_isli);
}
if($charges_type){
$query->where('charges_type', $charges_type);
}
})->where('is_deleted', 0)->field('batchcode')->select()->toArray();
if($batchcode_ids){
$where['batchcode'] = array_column($batchcode_ids, 'batchcode');
}else{
$where['batchcode'] = -1;
}
//}
$search = $this->buildSearch(['createtime', 'batchcode', 'buyisli', 'order'], $where);
$list = (new Order())->list($search, $where, $limit, []);
$list->each(function ($item){
$item['buy_username'] = OrderUser::where('islicode', $item['buy_islicode'])->where('batchcode', $item['batchcode'])->value('name');
$entrust_name = [];
$entrust_type = [];
$goods_name = "";
$order_detail = OrderGoodsDetail::where('batchcode', $item['batchcode'])->where('is_deleted', 0)->select();
$order_detail->each(function ($val) use(&$entrust_name, &$goods_name, &$entrust_type){
$username = OrderUser::where('islicode', $val['entrust_islicode'])->where('batchcode', $val['batchcode'])->value('name');
$entrust_name[] = $username;
if(!empty($goods_name)){
$goods_name .= ",".$val['goods_name'];
}else{
$goods_name = $val['goods_name'];
}
$entrust_type[] = ($val['goods_entrust'] == 1 ? '转让' : '授权');
return $val;
});
$item['entrust_name'] = implode(',', array_unique($entrust_name));
$item['entrust_type'] = implode(',', array_unique($entrust_type));
$item['goods_name'] = $goods_name;
return $item;
});
$list->visible(['id', 'batchcode', 'entrust_name', 'entrust_type', 'goods_name', 'buy_username', 'type', 'total_money', 'status', 'createtime']);
$list->hidden(['user']);
$list = $list->toArray();
$start = ($page - 1) * $limit + 1;
$end = $page * $limit;
if($list['total'] < $end){
$end = $list['total'];
}
if($list['total'] < $start){
$start = $end = $list['total'];
}
$list['start'] = $start;
$list['end'] = $end;
return $list;
}
public function orderDetail($batchcode){
$order = Order::alias('order')
->join('order_goods_detail order_detail', 'order_detail.batchcode = order.batchcode')
->join('goods goods', 'goods.goods_islicode = order_detail.goods_islicode')
->where('order.batchcode', $batchcode)
->where('order_detail.is_deleted', 0)
->field('order_detail.goods_image,order_detail.goods_name,order_detail.goods_islicode,order_detail.goods_type,order_detail.goods_entrust,
order_detail.goods_ownership_str,order_detail.contractual_period,order_detail.charges_type,order_detail.earnest_money,
order_detail.price,goods.contractual_start_time,goods.contractualtime_end_time,order_detail.entrust_islicode,
goods.islicode,order_detail.id as goods_detail_id,order_detail.service_charge,
order_detail.goods_price,order_detail.price,order_detail.transaction_count,order_detail.id as source_id,order_detail.money,order.batchcode,order_detail.contract_code,order.status')
->select()->toArray();
if(!$order){
throw new \think\Exception('未查询到该订单信息', 400);
}
$result = [];
foreach($order as $val){
if(!empty($val['goods_image'])){
$val['goods_image'] = $this->getOrderImageStatus($val['goods_image'], $val['goods_detail_id']);
}
$order_user = OrderUser::where('batchcode', $batchcode)->where('islicode', $val['entrust_islicode'])->find();
$order_user->hidden(['id', 'batchcode']);
$source_gather = OrderGoodsSource::where('detail_id', $val['source_id'])->where('is_deleted', 0)->select()->toArray();
$gather_arr = [];
$oneSource = [];
foreach($source_gather as $value){
$source_data = json_decode($value['source_data'], true);
if($value['datatype'] && !isset($gather_arr[ explode(' ', $value['sourceIdentify'])[1] ])){
$info = [
"name" => $value['source_name'],
"class" => $value['source_type'],
"registerDate" => $source_data['registerDate'],
"identifier" => $source_data['identifier'],
"count" => GoodsSource::where('goods_isli_code', $val['goods_islicode'])->where('datatype', 1)->where('is_deleted', 0)->whereLike('sourceIdentify', "%{$value['sourceIdentify']}%")->count(),
];
$gather_arr[explode(' ', $value['sourceIdentify'])[1]] = $info;
}elseif(!$value['datatype']){
$filesize = getSourceFileSize($source_data['metadataFileSize'] ?? 0);
$info = [
"name" => $value['source_name'],
"class" => $value['source_type'],
"registerDate" => $source_data['registerDate'],
"identifier" => $source_data['identifier'],
"filesize" => $filesize,
"metadataFileFormat" => $source_data['metadataFileFormat'] ?? ""
];
$source_download = OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)->where('goods_islicode', $val['goods_islicode'])->value('source_download');
$source_download = json_decode($source_download, true);
foreach($source_download as $item){
if($item['islicode'] == $value['linkcode']){
$info['download_status'] = $item['status'];
break;
}
}
$oneSource[] = $info;
}
}
$result[] = [
"userinfo" => $order_user,
"goods" => $val,
"gather_arr" => array_values($gather_arr),
"oneSource" => $oneSource,
];
}
return $result;
}
public function orderGoodsDetail($id){
$result = [];
$order_goods_detail = OrderGoodsDetail::where('id', $id)->where('is_deleted', 0)->find();
$result['entrust_goods'] = [
"goods_name" => $order_goods_detail['goods_name'],
"goods_islicode" => $order_goods_detail['goods_islicode'],
"goods_image" => $order_goods_detail['goods_image'],
"goods_type" => $order_goods_detail['goods_type'],
"goods_entrust" => $order_goods_detail['goods_entrust'],
"goods_ownership_str" => $order_goods_detail['goods_ownership_str'],
"contractual_period" => $order_goods_detail['contractual_period'],
"charges_type" => $order_goods_detail['charges_type'],
"earnest_money" => $order_goods_detail['earnest_money'],
"price" => $order_goods_detail['price']
];
$goods_source = OrderGoodsSource::where('detail_id', $id)->where('is_deleted', 0)->select()->toArray();
$source_name = "";
$source_type = "";
$allocationtime = "";
foreach($goods_source as &$val){
$id = $val['id'];
$source_name = $val['source_name'];
$allocationtime = date('Y-m-d', strtotime($val['allocationtime']));
if(!empty($val['target_data'])){
$val['target_data'] = json_decode($val['target_data'], true);
if(isset($val['target_data']['classification'])){
$source_type = $val['target_data']['classification'];
}
// $filesize = 0;
// if(isset($val['target_data']['metadataFileSize'])) {
// $filesize = round($val['target_data']['metadataFileSize'] / 1024 / 1024, 2);
// }
// $source = [
// "source_name" => $val['target_data']['titleName'],
// "islicode" => $val['target_data']['isliCode'],
// "relevancy_isli" => $val['target_data']['identifier'],
// "filesize" => $filesize,
// "format" => (isset($val['target_data']['metadataFileFormat']) ? $val['target_data']['metadataFileFormat'] : ''),
// "registerDate" => $val['target_data']['registerDate'],
// ];
// $result['entrust_goods']['source'][] = $source;
}
$val['source_data'] = json_decode($val['source_data'], true);
if(isset($val['source_data']['classification'])){
$source_type = $val['source_data']['classification'];
}
// if(empty($val['target_data'])){
// $filesize = 0;
// if(isset($val['source_data']['metadataFileSize'])) {
// $filesize = round($val['source_data']['metadataFileSize'] / 1024 / 1024, 2);
// }
// $source = [
// "source_name" => $val['source_data']['titleName'],
// "islicode" => $val['source_data']['isliCode'],
// "relevancy_isli" => $val['source_data']['identifier'],
// "filesize" => $filesize,
// "format" => (isset($val['source_data']['metadataFileFormat']) ? $val['source_data']['metadataFileFormat'] : ''),
// "registerDate" => $val['source_data']['registerDate'],
// ];
// $result['entrust_goods']['source'][] = $source;
// }
}
$result['source_gather']['linkCode'] = $order_goods_detail['goods_islicode'];
$result['source_gather']['source_count'] = count($goods_source);
$result['source_gather']['source_name'] = $source_name;
$result['source_gather']['source_type'] = $source_type;
$result['source_gather']['allocationtime'] = $allocationtime;
return $result;
}
public function invoiceList(){
}
public function getOrder($user_isli, $user_role, $pay_status, $close_status, $order_status, $createtime, $batchcode, $charges_type, $page, $limit){
$where = [];
// $where['order.is_deleted'] = 0;
if(!empty($batchcode)){
$where['order.batchcode'] = $batchcode;
}
if(!empty($pay_status)){
$where['pay_status'] = $pay_status;
}
if(!empty($close_status)){
// $where['close_status'] = $close_status;
$close_order = OrderGoodsDetail::where('close_status', 'in', $close_status)->where('is_deleted', 0)->field('batchcode')->select()->toArray();
$close_order = array_column($close_order, 'batchcode');
$where['close_status'] = $close_order;
}
if(!empty($order_status)){
$where['status'] = $order_status;
}
if(!empty($createtime)){
$where['createtime'] = $createtime;
}
if(!empty($charges_type)){
$where['total_money'] = $charges_type;
}
if($user_role == 1){
$where['order.buy_islicode'] = $user_isli;
// return $this->buyGetOrder($where);
}elseif($user_role == 2){
// 后续改成with
// $where['order.entrust_islicode'] = $user_isli;
if(!empty($user_isli)){
$order_detail = OrderGoodsDetail::where('entrust_islicode', $user_isli)->where('is_deleted', 0)->field('batchcode')->select()->toArray();
}else{
$order_detail = OrderGoodsDetail::field('batchcode')->where('is_deleted', 0)->select()->toArray();
}
$batchcode_ids = implode(',', array_column($order_detail, 'batchcode'));
if($batchcode_ids){
$where['batchcode'] = $batchcode_ids;
}else{
$where['batchcode'] = -1;
}
// if(!empty($user_isli)){
// return $this->entrustGetOrder($where, $user_isli);
// }else{
// return $this->buyGetOrder($where);
// }
}
$search_close_money = $this->getCloseMoney($where, $user_isli, $user_role);
$order = new Order();
$total_close_money = 0.00;
$search = $this->buildSearch(['batchcode', 'createtime', 'pay_status', 'close_status', 'status', 'order', 'total_money'], $where);
$result = $order->list($search, $where, $limit, []);
$result = $result->each(function($item, $key) use($user_isli, $user_role, &$total_close_money){
// $buy_username = User::where('user_isli', $item['buy_islicode'])->value('username');
// $item['entrust_username'] = $item['username'];
$buy_user = OrderUser::where('batchcode', $item['batchcode'])->where('islicode', $item['buy_islicode'])->find();
$item['buy_username'] = $buy_user->name;
$item['attesttime'] = $buy_user->attesttime;
$item['registertime'] = $buy_user->registertime;
$item['userType'] = $buy_user->userType;
$item['authType'] = $buy_user->authType;
$item['state'] = $buy_user->state;
$ratio_setting = AccountRatioSetting::where('id', $item['account_ratio_id'])->find();
$entrust_ratio_detail = AccountRatioDetail::where('setting_id', $ratio_setting->id)->where('role_type', 1)->find();
$entrust_number = 0;
if($entrust_ratio_detail['calculate'] == 1){
$entrust_number = $entrust_ratio_detail['ratio'];
}else{
$entrust_number = $entrust_ratio_detail['amount'];
}
if($user_role == 1){
if($entrust_number <= 0){
$total_close_money += round($item['total_money'], 2);
}else{
$total_close_money += round($item['total_money'] * ($entrust_number / 100), 2);
}
}
$total_money = 0;
$total_service_charge = 0;
$order_detail = OrderGoodsDetail::where('batchcode', $item['batchcode'])->where('is_deleted', 0)->where(function ($query) use($user_isli, $user_role){
if(!empty($user_isli) && $user_role == 2){
$query->where('entrust_islicode', $user_isli);
}
})->select();
$order_detail->each(function ($val) use(&$total_money, &$total_service_charge, &$user_role, &$total_close_money, &$entrust_number, &$item){
$item['close_status'] = $val['close_status'];
$entrust_user = OrderUser::where('batchcode', $val['batchcode'])->where('islicode', $val['entrust_islicode'])->find();
$val['entrust_name'] = $entrust_user->name;
$val['attesttime'] = $entrust_user->attesttime;
$val['registertime'] = $entrust_user->registertime;
$val['userType'] = $entrust_user->userType;
$val['authType'] = $entrust_user->authType;
$val['state'] = $entrust_user->state;
$goods_status = Goods::where('goods_islicode', $val['goods_islicode'])->value('goods_status');
if(!$goods_status){
$goods_status = 4;
}
$val['goods_status'] = $goods_status;
if($user_role == 2){
if($entrust_number <= 0){
$total_close_money += round($val['money'], 2);
}else{
$total_close_money += round($val['money'] * ($entrust_number / 100), 2);
}
}
if($val['goods_entrust'] == 1 || ($val['charges_type'] == 1 && $val['goods_entrust'] == 2)){
$val['transaction_count'] = "-";
}
$total_money += $val['money'];
$total_service_charge += $val['service_charge'];
// $entrust_name = User::where('user_isli', $val['entrust_islicode'])->value('username');
$val['entrust_month'] = $val['contractual_period'];
$source = OrderGoodsSource::where('detail_id', $val['id'])->select();
// $source->each(function ($val_source){
// if(!empty($val_source['target_data'])){
// $val_source['target_data'] = json_decode($val_source['target_data'], true);
// if(!empty($val_source['target_data']['source_url'])){
// var_dump($val_source['target_data']);die;
// $source_url =
// $source_url = json_decode($val_source['target_data']['source_url'], true);
// var_dump($source_url);die;
// $val_source['target_data']['source_url'] = $source_url;
// }
// }else{
// $val_source['source_data'] = json_decode($val_source['source_data'], true);
// }
// return $val_source;
// });
$source->hidden(['id', 'detail_id', 'batchcode', 'is_deleted']);
$val['source'] = $source->toArray();
// $val['entrust_name'] = $entrust_name;
return $val;
});
$item['total_money'] = round($total_money, 2);
$item['total_service_charge'] = round($total_service_charge, 2);
$item['close_money'] = round(($total_money - $total_service_charge) * ($entrust_number / 100), 2);
$order_detail->hidden(['id', 'goods_detail_id', 'user_id', 'batchcode', 'createtime', 'updatetime', 'is_deleted', 'data_json', 'source_json']);
$item['order_detail'] = $order_detail->toArray();
if($user_role == 1 && $item['status'] == 3){
$item['status'] = 4;
}
return $item;
});
$result->hidden(['goodsDetail', 'id', 'is_deleted', 'user_id', 'username', 'user_isli', 'user']);
$result = $result->toArray();
$result['search_close_money'] = round($search_close_money, 2);
$result['total_close_money'] = round($total_close_money, 2);
return $result;
}
public function getCloseMoney($where, $user_isli, $user_role){
$order = new Order();
$total_close_money = 0.00;
$search = $this->buildSearch(['batchcode', 'createtime', 'pay_status', 'close_status', 'status', 'order'], $where);
$result = $order->list($search, $where, "select", []);
$result->each(function($item, $key) use($user_isli, $user_role, &$total_close_money) {
$ratio_setting = AccountRatioSetting::where('id', $item['account_ratio_id'])->find();
$entrust_ratio_detail = AccountRatioDetail::where('setting_id', $ratio_setting->id)->where('role_type', 1)->find();
$entrust_number = 0;
if($entrust_ratio_detail['calculate'] == 1){
$entrust_number = $entrust_ratio_detail['ratio'];
}else{
$entrust_number = $entrust_ratio_detail['amount'];
}
if($user_role == 1){
if($entrust_number <= 0){
$total_close_money += round($item['total_money'], 2);
}else{
$total_close_money += round($item['total_money'] * ($entrust_number / 100), 2);
}
}else{
$money = OrderGoodsDetail::where('batchcode', $item['batchcode'])->where('is_deleted', 0)->where(function ($query) use($user_isli, $user_role){
if(!empty($user_isli) && $user_role == 2){
$query->where('entrust_islicode', $user_isli);
}
})->sum('money');
if($entrust_number <= 0){
$total_close_money += round($money, 2);
}else{
$total_close_money += round($money * ($entrust_number / 100), 2);
}
}
});
return $total_close_money;
}
public function entrustGetOrder($where, $user_isli){
$order = new Order();
$search = $this->buildSearch(['batchcode', 'createtime', 'pay_status', 'close_status', 'status'], $where);
$result = $order->list($search, $where, 'select', ['user', 'withJoin' => true]);
$result = $result->each(function($item, $key) use($user_isli){
// $buy_username = User::where('user_isli', $item['buy_islicode'])->value('username');
// $item['entrust_username'] = $item['username'];
$item['buy_username'] = $item['username'];
$total_money = 0;
$total_service_charge = 0;
$order_detail = OrderGoodsDetail::where('batchcode', $item['batchcode'])->where('is_deleted', 0)->where(function ($query) use($user_isli){
if(!empty($user_isli)){
$query->where('entrust_islicode', $user_isli);
}
})->select();
$order_detail->each(function ($val) use(&$total_money, &$total_service_charge){
$total_money += $val['money'];
$total_service_charge += $val['service_charge'];
$entrust_name = User::where('user_isli', $val['entrust_islicode'])->value('username');
$source = OrderGoodsSource::where('detail_id', $val['id'])->select();
$source->hidden(['id', 'detail_id', 'batchcode', 'is_deleted']);
$val['source'] = $source->toArray();
$val['entrust_name'] = $entrust_name;
return $val;
});
$item['total_money'] = $total_money;
$item['total_service_charge'] = $total_service_charge;
$item['close_money'] = round(($total_money - $total_service_charge) * 0.8, 2);
$order_detail->hidden(['id', 'goods_detail_id', 'batchcode', 'createtime', 'updatetime', 'is_deleted', 'data_json', 'source_json']);
$item['order_detail'] = $order_detail->toArray();
return $item;
});
$result->hidden(['goodsDetail', 'id', 'is_deleted', 'user_id', 'username', 'user_isli', 'user']);
$result->toArray();
return $result;
}
public function buyGetOrder($where){
$order = new Order();
$search = $this->buildSearch(['batchcode', 'createtime', 'pay_status', 'close_status', 'status'], $where);
$result = $order->list($search, $where, 'select', ['user', 'withJoin' => true]);
$result = $result->each(function($item, $key){
// $buy_username = User::where('user_isli', $item['buy_islicode'])->value('username');
// $item['entrust_username'] = $item['username'];
$item['buy_username'] = $item['username'];
$order_detail = OrderGoodsDetail::where('batchcode', $item['batchcode'])->where('is_deleted', 0)->select();
$order_detail->each(function ($val){
$entrust_name = User::where('user_isli', $val['entrust_islicode'])->value('username');
$source = OrderGoodsSource::where('detail_id', $val['id'])->select();
$source->hidden(['id', 'detail_id', 'batchcode', 'is_deleted']);
$val['source'] = $source->toArray();
$val['entrust_name'] = $entrust_name;
return $val;
});
$order_detail->hidden(['id', 'goods_detail_id', 'batchcode', 'createtime', 'updatetime', 'is_deleted', 'data_json', 'source_json']);
$item['order_detail'] = $order_detail->toArray();
return $item;
});
$result->hidden(['goodsDetail', 'id', 'is_deleted', 'user_id', 'username', 'user_isli', 'user']);
$result->toArray();
return $result;
}
public function createOrder($user_isli, $goods){
if($this->redis->get("createOrder_" . $_SERVER['HTTP_SIGN'])){
throw new \think\Exception('请勿重复提交', 400);
}
$this->redis->set("createOrder_" . $_SERVER['HTTP_SIGN'], 1, 10);
$user = User::where('user_isli', $user_isli)->find();
if(!$user){
// throw new \think\Exception('没有该用户', 400);
}
$car = $this->redis->get('car_'.$user_isli);
if(count($goods) == 1){
$batchcode = $this->buyFindGoods($user_isli, $goods[0]['goods_isli'], $goods[0]['use_years']);
if(!empty($car)){
$car = unserialize(stripslashes($car));
$new_car = [];
foreach($car as $j){
if(!in_array($j['goods_isli'], [$goods[0]['goods_isli']])){
$new_car[] = [
'goods_isli' => $j['goods_isli'],
'use_years' => $j['use_years'],
];
}
}
if(count($new_car) > 0){
$this->redis->set('car_'.$user_isli, serialize($new_car));
}else{
$this->redis->del('car_'.$user_isli);
}
}
}else{
$batchcode = $this->buyCarGoods($user_isli, $goods);
if(!empty($car)){
$car = unserialize(stripslashes($car));
$goods_ids = array_column($goods, 'goods_isli');
$new_car = [];
foreach($car as $j){
if(!in_array($j['goods_isli'], $goods_ids)){
$new_car[] = [
'goods_isli' => $j['goods_isli'],
'use_years' => $j['use_years'],
];
}
}
if(count($new_car) > 0){
$this->redis->set('car_'.$user_isli, serialize($new_car));
}else{
$this->redis->del('car_'.$user_isli);
}
}
}
$where = [];
$where['batchcode'] = $batchcode;
$search = $this->buildSearch([], $where);
$order = new Order();
$result = $order->list($search, $where, 'find', []);
$buy_userinfo = OrderUser::where('islicode', $user_isli)->where('batchcode', $batchcode)->find();
$buy_userinfo->hidden(['tickettime', 'ticketid', 'ticketmoney', 'ticketurl', 'ticketimage', 'ticket_status', 'id']);
$result->buy_userinfo = $buy_userinfo->toArray();
$result->buy_username = $result->buy_userinfo['name'];
$order_detail = OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)->select();
$order_detail->each(function ($item){
$entrust_userinfo = OrderUser::where('islicode', $item['entrust_islicode'])->where('batchcode', $item['batchcode'])->find();
$entrust_userinfo->hidden(['tickettime', 'ticketid', 'ticketmoney', 'ticketurl', 'ticketimage', 'ticket_status', 'id']);
$source = OrderGoodsSource::where('detail_id', $item['id'])->select();
$source->hidden(['id', 'detail_id', 'batchcode', 'is_deleted']);
$item['source'] = $source->toArray();
$item['entrust_month'] = $item['contractual_period'];
$item['entrust_username'] = $entrust_userinfo->name;
$item['entrust_userinfo'] = $entrust_userinfo->toArray();
if($item['goods_entrust'] == 1 || ($item['charges_type'] == 1 && $item['goods_entrust'] == 2)){
$item['transaction_count'] = "-";
}
return $item;
});
$order_detail->hidden(['id', 'goods_detail_id', 'batchcode', 'createtime', 'updatetime', 'is_deleted', 'data_json', 'source_json', 'user_id']);
$result->order_detail = $order_detail->toArray();
$result->hidden(['id', 'is_deleted', 'user_id', 'username', 'user_isli', 'user', 'user__id', 'user__username', 'user__user_isli', 'user__agency_type', 'user__attest_status', 'user__registertime', 'user__attesttime']);
if(!$this->redis->del("createOrder_" . $_SERVER['HTTP_SIGN'])){
throw new \think\Exception('请勿重复提交', 400);
}
return $result->toArray();
// $where = [];
// $where['batchcode'] = $batchcode;
// $search = $this->buildSearch(['batchcode'], $where);
// $order = new Order();
// $result = $order->list($search, $where, 'select', []);
// $result->each(function ($item){
// $buy_user = OrderUser::where('batchcode', $item['batchcode'])->where('islicode', $item['buy_islicode'])->find();
// $item['buy_username'] = $buy_user->name;
// $item['attesttime'] = $buy_user->attesttime;
// $item['registertime'] = $buy_user->registertime;
// $item['userType'] = $buy_user->userType;
// $item['state'] = $buy_user->state;
//
// $total_money = 0;
// $total_service_charge = 0;
//
// $order_detail = OrderGoodsDetail::where('batchcode', $item['batchcode'])->select();
// $order_detail->each(function ($val) use(&$total_money, &$total_service_charge){
// $entrust_user = OrderUser::where('batchcode', $val['batchcode'])->where('islicode', $val['entrust_islicode'])->find();
// $val['entrust_name'] = $entrust_user->name;
// $total_money += $val['money'];
// $total_service_charge += $val['service_charge'];
//// $entrust_name = User::where('user_isli', $val['entrust_islicode'])->value('username');
// $val['earnest_money'] = $val['contractual_period'];
// $source = OrderGoodsSource::where('detail_id', $val['id'])->select();
// $source->hidden(['id', 'detail_id', 'batchcode', 'is_deleted']);
// $val['source'] = $source->toArray();
//// $val['entrust_name'] = $entrust_name;
// return $val;
// });
// $item['total_money'] = $total_money;
// $item['total_service_charge'] = $total_service_charge;
// $item['close_money'] = round(($total_money - $total_service_charge) * 0.8, 2);
// $order_detail->hidden(['id', 'goods_detail_id', 'batchcode', 'createtime', 'updatetime', 'is_deleted', 'data_json', 'source_json']);
// $item['order_detail'] = $order_detail->toArray();
// return $item;
// });
// $result->hidden(['goodsDetail', 'id', 'is_deleted', 'user_id', 'username', 'user_isli', 'user']);
// return $result->toArray();
}
public function buyFindGoods($user_isli, $goods_islicode, $goods_use_years){
$goods = Goods::where('goods_islicode', $goods_islicode)->where('is_deleted', 0)->find();
if(!$goods){
throw new \think\Exception('没有该标的', 400);
}
$goods_detail = GoodsDetail::where('id', $goods->goods_detail_id)->find();
$count = $goods_use_years;
if($goods_detail->goods_entrust == 1){
$count = 1;
}
$ratio_setting = AccountRatioSetting::where('is_deleted', 0)->where('status', 1)->find();
$ratio_detail = AccountRatioDetail::where('setting_id', $ratio_setting->id)->where('role_type', 2)->find();
$this->checkOrder($goods, $goods_detail, $user_isli, $goods_islicode, $goods_use_years);
// 检查商品是否有库存购买
if($goods_detail['charges_type'] == 2){
// 付费
if($ratio_detail->calculate == 1){
// 比例
if($ratio_detail->ratio <= 0){
$service_charge = 0;
}else{
$service_charge = $count * $goods_detail['price'] * ($ratio_detail->ratio / 100);
}
}else{
// 固定
$service_charge = $count * $goods_detail['price'] + $ratio_detail->amount;
}
$total_money = ($count * $goods_detail['price']) + $service_charge + $goods_detail['earnest_money'];
$status = 1;
$pay_status = 1;
}else{
// 免费
$service_charge = 0;
$total_money = 0;
$status = 2;
$pay_status = 2;
}
// var_dump($total_money);die;
$batchcode = $this->createOrderBatchcode();
$this->insertOrderDetail($batchcode, $goods_islicode, $goods['islicode'], $goods["user_islicode"], $service_charge, $goods_use_years, $total_money, $goods_detail, $ratio_setting->id, $count);
$user_id = $this->addOrderUser($batchcode, $user_isli, 1);
$order = [
"batchcode" => $batchcode,
"user_id" => $user_id,
"buy_islicode" => $user_isli,
// "order_islicode" => $this->getOrderCode(),
"total_service_charge" => $service_charge,
"total_money" => $total_money,
"type" => 1,
"status" => $status,
"pay_status" => $pay_status,
"account_ratio_id" => $ratio_setting->id,
];
if($goods_detail['charges_type'] == 1){
$order['paymenttime'] = date('Y-m-d H:i:s');
}
if((new Order())->insert($order)){
if($status == 2){
$pay = new PayService();
$pay->payFinishOperate($batchcode);
}
$buy_account_close = [
"user_isli" => $user_isli,
"batchcode" => $batchcode,
"order_user_id" => $user_id,
"service_charge" => $service_charge,
"thatday_buy_money" => $total_money,
];
(new UserAccountBill())->insert($buy_account_close);
if($goods_detail->goods_entrust == 1 || ($goods_detail->contractual_period == 2 && $goods_detail->goods_entrust != 2)){
if(GoodsDetail::where('id', $goods->goods_detail_id)->where('stock', '>=',$goods_detail->stock)->dec('stock')->update()){
$status_str = "";
if($goods_detail->goods_entrust == 1){
$goods->goods_status = 5;
$status_str = "暂停";
}else{
$goods->goods_status = 2;
$status_str = "下架";
}
$goods->save();
$buy_username = OrderUser::where('id', $user_id)->value('name');
$operation_log = [
"type" => "goods",
"log_id" => $goods->id,
"message" => date('Y-m-d H:i:s')." 用户{$buy_username}下单,{$status_str}该委托标的",
];
(new OperationLog())->insert($operation_log);
return $batchcode;
}else{
throw new \think\Exception('标的已卖完', 400);
}
}else{
return $batchcode;
}
}
}
public function buyCarGoods($user_isli, array $car = []){
// $batchcodes = [];
// // 对购物车进行循环
// foreach($car as $key => $val){
// $goods_islicode = $val['goods_isli']; // 商品标识码
// $goods_use_years = $val['use_years']; // 购买使用年限
// $batchcode = $this->buyFindGoods($user_isli, $goods_islicode, $goods_use_years);
// $batchcodes[] = $batchcode;
// }
// return $batchcodes;
$total_service_charge = 0;
$total_money = 0;
$batchcode = $this->createOrderBatchcode();
$ratio_setting = AccountRatioSetting::where('is_deleted', 0)->where('status', 1)->find();
$ratio_detail = AccountRatioDetail::where('setting_id', $ratio_setting->id)->where('role_type', 2)->find();
$user_id = $this->addOrderUser($batchcode, $user_isli, 1);
$buy_username = OrderUser::where('id', $user_id)->value('name');
// 对购物车进行循环
foreach($car as $key => $val){
$goods_islicode = $val['goods_isli']; // 商品标识码
$goods_use_years = $val['use_years']; // 购买使用年限
$goods = Goods::where('goods_islicode', $goods_islicode)->where('is_deleted', 0)->find();
if(!$goods){
throw new \think\Exception('没有该标的', 400);
}
$goods_detail = GoodsDetail::where('id', $goods->goods_detail_id)->find();
// 判断商品状态
$this->checkOrder($goods, $goods_detail, $user_isli, $goods_islicode, $goods_use_years);
// 检查商品是否有库存购买
if($goods_detail->goods_entrust == 1 || ($goods_detail->contractual_period == 2 && $goods_detail->goods_entrust != 2)){
if (!GoodsDetail::where('id', $goods->goods_detail_id)->where('stock', '>=', $goods_detail->stock)->dec('stock')->update()) {
throw new \think\Exception('标的已卖完,标的标识码:' . $goods_islicode, 400);
}
$status_str = "";
if($goods_detail->goods_entrust == 1){
$goods->goods_status = 5;
$status_str = "暂停";
}else{
$goods->goods_status = 2;
$status_str = "下架";
}
$goods->save();
$operation_log = [
"type" => "goods",
"log_id" => $goods->id,
"message" => date('Y-m-d H:i:s')." 用户{$buy_username}下单,{$status_str}该委托标的",
];
(new OperationLog())->insert($operation_log);
}
$count = $goods_use_years;
if($goods_detail->goods_entrust == 1){
$count = 1;
}
if($goods_detail['charges_type'] == 2){
// 付费
if($ratio_detail->calculate == 1){
// 比例
if($ratio_detail->ratio <= 0){
$service_charge = 0;
}else{
$service_charge = $count * $goods_detail['price'] * ($ratio_detail->ratio / 100);
}
}else{
// 固定
$service_charge = $count * $goods_detail['price'] + $ratio_detail->amount;
}
$money = ($count * $goods_detail['price']) + $service_charge + $goods_detail['earnest_money'];
$total_service_charge += $service_charge;
$total_money += $money;
}else{
// 免费
$service_charge = 0;
$money = 0;
}
$this->insertOrderDetail($batchcode, $goods_islicode, $goods['islicode'], $goods["user_islicode"], $service_charge, $goods_use_years, $money, $goods_detail, $ratio_setting->id, $count);
}
$order = [
"batchcode" => $batchcode,
"user_id" => $user_id,
"buy_islicode" => $user_isli,
// "order_islicode" => $this->getOrderCode(),
"total_service_charge" => $total_service_charge,
"total_money" => $total_money,
"type" => 1,
"account_ratio_id" => $ratio_setting->id,
];
if($total_money <= 0){
$order['status'] = 2;
$order['pay_status'] = 2;
$order['paymenttime'] = date('Y-m-d H:i:s');
}
if((new Order())->insert($order)){
$pay = new PayService();
$pay->payFinishOperate($batchcode);
$buy_account_close = [
"user_isli" => $user_isli,
"batchcode" => $batchcode,
"order_user_id" => $user_id,
"service_charge" => $total_service_charge,
"thatday_buy_money" => $total_money,
];
(new UserAccountBill())->insert($buy_account_close);
return $batchcode;
}
}
public function insertOrderDetail($batchcode, $goods_islicode, $islicode, $entrust_islicode, $service_charge, $goods_use_years, $total_money, $goods_detail, $ratio_setting, $count){
$user_id = OrderUser::where('batchcode', $batchcode)->where('islicode', $entrust_islicode)->value('id');
if(!$user_id){
$user_id = $this->addOrderUser($batchcode, $entrust_islicode);
}
$ratio_detail = AccountRatioDetail::where('setting_id', $ratio_setting)->where('role_type', 3)->find();
// 订单商品明细
$order_goods_detail = [
"user_id" => $user_id,
"batchcode" => $batchcode,
"goods_islicode" => $goods_islicode,
"islicode" => $islicode,
"entrust_islicode" => $entrust_islicode,
"goods_name" => $goods_detail['goods_name'],
"goods_image" => $goods_detail['goods_image'],
"identifier" => $goods_detail['identifier'],
"identifiers" => $goods_detail['identifiers'],
"sourcedata_islicode" => $goods_detail['sourcedata_islicode'],
"price" => $goods_detail['price'],
"goods_price" => $goods_detail['price'] * $count,
"service_charge" => $service_charge,
"earnest_money" => 0,
"transaction_count" => $goods_use_years,
"money" => $total_money,
"goods_ownership_str" => $goods_detail['goods_ownership_str'],
"goods_type" => $goods_detail['goods_type'],
"charges_type" => $goods_detail['charges_type'],
"goods_entrust" => $goods_detail['goods_entrust'],
"contractual_period" => $goods_detail['contractual_period'],
"transaction_class" => $goods_detail['transaction_class'],
"contract" => $goods_detail['contract'],
"otherIdentifiers" => $goods_detail['goods_name'],
"data_json" => $goods_detail['data_json'],
"source_json" => $goods_detail['source_json'],
'classification' => $goods_detail['classification'],
];
$order_detail_service = round($order_goods_detail['goods_price'] * ($ratio_detail->ratio / 100), 2);
$order_goods_detail['entrust_service_charge'] = $order_detail_service;
$order_goods_detail['entrust_money'] = $order_goods_detail['entrust_service_charge'] + $order_goods_detail['goods_price'];
$identifiers = explode(',', $goods_detail['identifiers']);
$source_url_arr = [];
for($i=0;$i<count($identifiers);$i++){
$source_url_arr[] = [
"url" => "",
"islicode" => $identifiers[$i],
"status" => 1
];
}
$order_goods_detail['source_download'] = json_encode($source_url_arr);
if( !($detail_id = (new OrderGoodsDetail())->insertGetId($order_goods_detail))){
throw new \think\Exception('下单失败,请稍后再试', 400);
}
$entrust_account_close = [
"user_isli" => $entrust_islicode,
"batchcode" => $batchcode,
"order_user_id" => $user_id,
"service_charge" => $order_detail_service,
"thatday_sale_money" => $goods_detail['price'],
];
(new UserAccountBill())->insert($entrust_account_close);
// 订单商品资源
$source = GoodsSource::where('goods_isli_code', $goods_islicode)->where('is_deleted', 0)->select();
$source->hidden(['id', 'goods_isli_code', 'is_deleted']);
$source = $source->toArray();
foreach($source as $k => $v){
if(!empty($v['source_data'])){
$v['source_data'] = json_decode($v['source_data'], true);
$v['source_data']['source_url'] = "";
$v['source_data']['source_status'] = 0;
$v['source_data'] = json_encode($v['source_data']);
}
if(!empty($v['target_data'])){
$v['target_data'] = json_decode($v['target_data'], true);
$v['target_data']['source_url'] = "";
$v['target_data']['source_status'] = 0;
$v['target_data'] = json_encode($v['target_data']);
}
$v['batchcode'] = $batchcode;
$v['detail_id'] = $detail_id;
if(!(new OrderGoodsSource())->insert($v)){
throw new \think\Exception('下单失败,请稍后再试', 400);
}
}
return true;
}
public function addOrderUser($batchcode, $user_isli, $is_buy = 0){
$userService = new UserService();
$userinfo = $userService->getApiUser($user_isli);
if(count($userinfo) <= 0){
throw new \think\Exception('未查询到用户信息,下单失败', 400);
}
if($is_buy == 1){
if($userinfo['userType'] == "个人"){
throw new \think\Exception('暂不支持个人用户交易', 400);
}
if($userinfo['state'] != 1){
throw new \think\Exception('当前用户未认证成功', 400);
}
}
if($userinfo['userType'] == "机构"){
$res = [
"batchcode" => $batchcode,
"userType" => $userinfo['userType'],
"state" => $userinfo['state'],
"islicode" => $userinfo['islicode'],
"name" => $userinfo['name'],
"uscc" => $userinfo['uscc'],
"legalsName" => $userinfo['legalsName'],
"legalsType" => $userinfo['legalsType'],
"legalsIdnum" => $userinfo['legalsIdnum'],
"legalsCellPhone" => (isset($userinfo['legalsCellPhone']) ? $userinfo['legalsCellPhone'] : ''),
"publicAccount" => $userinfo['publicAccount'],
"bankCardType" => $userinfo['bankCardType'],
"bankName" => $userinfo['bankName'],
"bankType" => $userinfo['bankType'],
"bankAccountName" => $userinfo['bankAccountName'],
"certIdnum" => $userinfo['certIdnum'],
"bankCellPhone" => $userinfo['bankCellPhone'],
"bankAddress" => $userinfo['bankAddress'],
// "registertime" => $userinfo['registerTime'],
// "attesttime" => $userinfo['authTime'],
// "auth_type" => $userinfo['authType'],
];
}else{
$res = [
"batchcode" => $batchcode,
"userType" => $userinfo['userType'],
"state" => $userinfo['state'],
"islicode" => $userinfo['islicode'],
"name" => $userinfo['name'],
"certType" => $userinfo['certType'],
"idNumber" => $userinfo['idNumber'],
"cellPhone" => $userinfo['cellPhone'],
"publicAccount" => $userinfo['publicAccount'],
"bankCardType" => $userinfo['bankCardType'],
"bankName" => $userinfo['bankName'],
"bankAccountName" => $userinfo['bankAccountName'],
"certIdnum" => $userinfo['certIdnum'],
"bankCellPhone" => $userinfo['bankCellPhone'],
"bankAddress" => $userinfo['bankAddress'],
];
}
if(isset($userinfo['registerTime'])){
$res['registertime'] = $userinfo['registerTime'];
}
if(isset($userinfo['authTime'])){
$res['attesttime'] = $userinfo['authTime'];
}
if(isset($userinfo['authType'])){
$res['authType'] = $userinfo['authType'];
}
return (new OrderUser())->insertGetId($res);
}
protected function checkOrder($goods, $goods_detail, $user_isli, $goods_islicode, $goods_use_years){
if(time() < strtotime(date('Y-m-d 09:00:00')) || time() > strtotime(date('Y-m-d 18:00:00'))){
throw new \think\Exception('非正常交易日时间,请在交易日内进行交易,交易日时间为周一至周日9:00-18:00', 400);
}
if(!$goods){
throw new \think\Exception('该标的已撤销,标的ISLI标识码:'.$goods_islicode, 400);
}
if($goods->user_islicode == $user_isli){
throw new \think\Exception('您是标的的授权方,不可购买,标的ISLI标识码:'.$goods_islicode, 400);
}
if($goods->goods_status != 1){
throw new \think\Exception('该标的现不在上架中,标的ISLI标识码:'.$goods_islicode, 400);
}
if($goods->contract_status != 1){
throw new \think\Exception('标的未申请合约关联,不可购买,标的ISLI标识码:'.$goods_islicode, 400);
}
if($goods_detail->stock <= 0 && $goods_detail->goods_entrust == 1){
throw new \think\Exception('标的库存为0,不可购买,标的ISLI标识码:'.$goods_islicode, 400);
}
if($goods_detail->contractual_period == 3){
if(strtotime($goods->contractual_start_time) > time() || strtotime($goods->contractualtime_end_time) < time()){
throw new \think\Exception('标的委托已结束,标的ISLI标识码:'.$goods_islicode, 400);
}
}
$order = Order::alias('order')->join('order_goods_detail detail', 'order.batchcode = detail.batchcode')
->where('order.buy_islicode', $user_isli)
->where('order.status', '<>', 5)
->where('detail.is_deleted', 0)
->where('detail.goods_islicode', $goods_islicode)
->field('order.status')->find();
if($order){
if($order->status == 1){
throw new \think\Exception('您的待付款订单中有标的:'.$goods_islicode.",请勿重复下单", 400);
}elseif($order->status == 2){
throw new \think\Exception('您的未完成订单中有标的:'.$goods_islicode.",请勿重复下单", 400);
}else{
throw new \think\Exception('您的已完成订单中有标的:'.$goods_islicode.",请勿重复下单", 400);
}
}
// $batchcodes = Order::where('buy_islicode', $user_isli)->where('status', '<>', 5)->field('status,batchcode')->select()->toArray();
// if($batchcodes){
// foreach($batchcodes as $val){
// $order_detail = OrderGoodsDetail::where('goods_islicode', $goods_islicode)->where('batchcode', $val['batchcode'])->value('id');
// if($order_detail && $val['status'] == 1){
// throw new \think\Exception('您的待付款订单中有标的:'.$goods_islicode.",请勿重复下单", 400);
// }elseif ($order_detail){
// throw new \think\Exception('您的未完成订单中有标的:'.$goods_islicode.",请勿重复下单", 400);
// }
// }
//
// }
return true;
}
public function getTicket($user_isli, $batchcode, $ticket_status, $tickettime){
// $entrust_batchcode = OrderGoodsDetail::where('entrust_islicode', $user_isli)->field('batchcode')->select()->toArray();
// $entrust_batchcode = array_column($entrust_batchcode, 'batchcode');
// $buy_batchcode = Order::where('buy_islicode', $user_isli)->field('batchcode')->select()->toArray();
// $buy_batchcode = array_column($buy_batchcode, 'batchcode');
// $batchcode_arr = array_merge($entrust_batchcode, $buy_batchcode);
// if(!empty($batchcode)){
// if(in_array($batchcode, $batchcode_arr)){
// $batchcode_arr = [$batchcode];
// }else{
// $batchcode_arr = [-1];
// }
// }
// $batchcode_ids = implode(',', $batchcode_arr);
// if(empty($batchcode_ids)){
// $batchcode_ids = '-1';
// }
$pdf_path = (new PayService())->initDir();
$where = [];
if($user_isli){
$where['islicode'] = $user_isli;
}
if($batchcode){
$where['batchcode'] = $batchcode;
}
if($ticket_status){
$where['ticket_status'] = $ticket_status;
}
$fields = ['batchcode', 'ticket_status', 'tickettime', 'ticketid', 'ticketmoney', 'ticketurl', 'pdfUrl'];
$result = Ticket::where($where)->where('ticket_status', '<>', 5)->where(function ($query) use($tickettime){
if(!empty($tickettime)){
if (isset($tickettime[1]) && preg_match("/^\d{4}-\d{2}-\d{2}$/", $tickettime[1])){
$tickettime[1] = $tickettime[1] . ' 23:59:59';
}
if (isset($tickettime[0]) && isset($tickettime[1]) && $tickettime[0] && $tickettime[1]){
$query->whereBetweenTime('tickettime', $tickettime[0], $tickettime[1]);
}elseif (isset($tickettime[0]) && $tickettime[0]){
$query->whereTime('tickettime', '>=', $tickettime[0]);
}elseif (isset($tickettime[1]) && $tickettime[1]){
$query->whereTime('tickettime', '<=', $tickettime[1]);
}
}
})->field($fields)->order('tickettime', 'desc')->select();
$result->each(function ($item) use($pdf_path){
if(empty($item['ticketurl']) && !empty($item['pdfUrl'])){
$status = get_headers($item['pdfUrl']);
$ticketurl = "";
if(strpos($status[0], "200")) {
$pdf_content = file_get_contents($item['pdfUrl']);
file_put_contents('./' . $pdf_path . "{$item['ticketid']}.pdf", $pdf_content);
$ticketurl = $pdf_path . "{$item['ticketid']}.pdf";
}
if($ticketurl){
Ticket::where('id', $item['id'])->update(['ticketurl' => $ticketurl]);
$item['ticketurl'] = env('app.host') . $ticketurl;
}
}elseif (!empty($item['ticketurl'])){
$item['ticketurl'] = env('app.host') . $item['ticketurl'];
}
$status = Order::where('batchcode', $item['batchcode'])->value('status');
$contract_code = OrderGoodsDetail::where('batchcode', $item['batchcode'])->where('is_deleted', 0)->field('contract_code')->select()->toArray();
$item['status'] = $status;
$item['contract_code'] = $contract_code;
return $item;
});
return $result;
}
public function getBalance($user_isli, $batchcode, $payee_name, $payee_bank, $payee_account){
if($this->redis->get($batchcode . $user_isli)){
throw new \think\Exception("正在处理,请勿重复提交", 400);
}
$this->redis->set($batchcode . $user_isli, 1, 10);
$order = Order::where('batchcode', $batchcode)->find();
if(!$order){
throw new \think\Exception("没有该订单", 400);
}
if($order->status != 3){
throw new \think\Exception("订单状态错误", 400);
}
// if($order->close_status == 1 || $order->close_status == 4){
// throw new \think\Exception("正在结算中,请勿重复操作", 400);
// return ['close_status' => $order->close_status];
// }
$user = (new UserService())->getApiUser($user_isli);
if(isset($user['name']) && $user['name'] != $payee_name){
OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)->where('entrust_islicode', $user_isli)->update(['close_status' => 3, 'callback_msg' => '-']);
return ['close_status' => 3];
}
// if($order->close_status == 4){
// throw new \think\Exception("已结算完毕,请勿重复操作", 400);
// }
$res = $this->createOrderClose($user_isli, $batchcode, $payee_name, $payee_bank, $payee_account, $order);
$this->redis->del($batchcode . $user_isli);
return $res;
}
public function orderInfo($batchcode){
$result = [];
$order = Order::where('batchcode', $batchcode)->find();
if(!$order){
throw new \think\Exception("未找到该订单", 400);
}
// $buy_username = OrderUser::where('islicode', $order['buy_islicode'])->where('batchcode', $batchcode)->value('username');
$order_detail = OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)
->field('entrust_islicode,goods_name,goods_type,goods_entrust,goods_ownership_str,price,transaction_count,earnest_money,service_charge,contract_code,close_serial_number')
->select()->toArray();
$entrust_name = [];
$goods_name = "";
$goods_type = "";
$goods_entrust = [];
$goods_ownership_str = "";
$price = 0;
$transaction_count = 0;
$earnest_money = 0;
$service_charge = 0;
$contract_code = "";
$close_serial_number = "";
foreach($order_detail as $item){
$username = OrderUser::where('islicode', $item['entrust_islicode'])->where('batchcode', $batchcode)->value('name');
$entrust_name[] = $username;
$goods_name .= $item['goods_name'] . ",";
$goods_type .= ($item['goods_type'] == 1 ? "文化资源数据," : "文化数字内容,");
$goods_entrust[] = ($item['goods_entrust'] == 1 ? "转让" : "授权");
$goods_ownership_str .= $item['goods_ownership_str'].",";
$price += $item['price'];
$transaction_count += $item['transaction_count'];
$earnest_money += $item['earnest_money'];
$service_charge += $item['service_charge'];
$contract_code .= $item['contract_code'].',';
$close_serial_number .= $item['close_serial_number'].",";
}
$entrust_name = implode(',', array_unique($entrust_name));
$result['order'] = $order;
// $result['order_info']['buy_username'] = $buy_username;
// $result['order_info']["buy_islicode"] = $order['buy_islicode'];
$result['order_info']['entrust_name'] = $entrust_name;
$result['order_info']['type'] = 1;
$result['order_info']['batchcode'] = $batchcode;
$result['order_info']['contract_code'] = rtrim($contract_code, ',');
$result['order_info']['close_serial_number'] = rtrim($close_serial_number, ',');
$result['order_info']['goods_name'] = rtrim($goods_name, ',');
$result['order_info']['goods_type'] = rtrim($goods_type, ',');
$result['order_info']['goods_entrust'] = implode(',', array_unique($goods_entrust));
$result['order_info']['goods_ownership_str'] = rtrim($goods_ownership_str, ',');
$result['order_info']['price'] = $price;
$result['order_info']['transaction_count'] = $transaction_count;
$result['order_info']['earnest_money'] = $earnest_money;
$result['order_info']['service_charge'] = $service_charge;
$result['order_info']['total_money'] = $order['total_money'];
$result['order']['goods_price'] = sprintf("%.2f", OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)->sum('goods_price'));
$result['buyuser'] = OrderUser::where('islicode', $order['buy_islicode'])->where('batchcode', $batchcode)->find()->hidden(['id']);
// 分账比例
$result['ratio_setting'] = $this->getRatio($order['account_ratio_id']);
// 资金结算表
$closeTable = $this->getCloseTable($order, $order_detail);
$result['close'] = $closeTable;
// 发票
$bill = $this->getBill($batchcode);
$result['bill'] = $bill;
return $result;
}
public function getRatio($id){
$setting = AccountRatioSetting::where('id', $id)->find();
$detail = AccountRatioDetail::where('setting_id', $id)->select()->toArray();
$arr = [];
foreach($detail as $val){
if($val['role_type'] == 1){
$arr[1] = $val;
}elseif($val['role_type'] == 2){
$arr[0] = $val;
}else{
$arr[2] = $val;
}
}
$setting['detail'] = $arr;
return $setting;
}
public function getCloseTable($order, $order_detail){
// $order_close = OrderClose::where('batchcode', $batchcode)->select()->toArray();
// return $order_close;
$result = [];
$platform_service_charge = 0;
$buy_user = OrderUser::where('batchcode', $order['batchcode'])->where('islicode', $order['buy_islicode'])->value('name');
$result[] = [
"close_side" => $buy_user,
"close_message" => "标的价款",
"money" => "-".(sprintf("%.2f", $order['total_money'] - $order['total_service_charge'])),
"tax_rate" => "-",
"tax_rate_money" => "-",
"close_money" => "-" . (sprintf("%.2f", $order['total_money'] - $order['total_service_charge'])),
"close_status" => $order['status'] > 1 ? ($order['status'] == 5 ? 1 : 2) : 1,
"close_number" => !empty($order['payid']) ? $order['payid'] : "-",
];
$result[] = [
"close_side" => $buy_user,
"close_message" => "交易佣金",
"money" => "-{$order['total_service_charge']}",
"tax_rate" => "6%",
"tax_rate_money" => "-",
"close_money" => "-{$order['total_service_charge']}",
"close_status" => $order['status'] > 1 ? ($order['status'] == 5 ? 1 : 2) : 1,
"close_number" => !empty($order['payid']) ? $order['payid'] : "-",
];
$platform_service_charge += $order['total_service_charge'];
$account_ratio_id = Order::where('batchcode', $order['batchcode'])->value('account_ratio_id');
$ratio_detail = AccountRatioDetail::where('setting_id', $account_ratio_id)->where('role_type', 3)->find();
$entrust_ratio_detail = AccountRatioDetail::where('setting_id', $account_ratio_id)->where('role_type', 1)->find();
$entrust_user = OrderUser::where('batchcode', $order['batchcode'])->where('islicode', '<>', $order['buy_islicode'])->field('batchcode,islicode,name')->select()->toArray();
foreach($entrust_user as $val){
$service_charge = OrderGoodsDetail::where('batchcode', $val['batchcode'])->where('is_deleted', 0)->where('entrust_islicode', $val['islicode'])->sum('goods_price');
$money = OrderGoodsDetail::where('batchcode', $val['batchcode'])->where('is_deleted', 0)->where('entrust_islicode', $val['islicode'])->sum('money');
$close_serial_number = OrderGoodsDetail::where('batchcode', $val['batchcode'])->where('is_deleted', 0)->where('entrust_islicode', $val['islicode'])->value('close_serial_number');
$result[] = [
"close_side" => $val['name'],
"close_message" => "标的价款",
"money" => "+".(sprintf("%.2f", $service_charge)),
"tax_rate" => "-",
"tax_rate_money" => "-",
"close_money" => "+".(sprintf("%.2f", $service_charge)),
"close_status" => $order['status'] == 4 ? 3 : 4,
"close_number" => !empty($close_serial_number) ? $close_serial_number : "-",
];
$platform_service_charge += $entrust_service_charge = sprintf("%.2f", ($service_charge * ($ratio_detail->ratio / 100)));
$result[] = [
"close_side" => $val['name'],
"close_message" => "交易佣金",
"money" => "-". $entrust_service_charge,
"tax_rate" => "6%",
"tax_rate_money" => "-",
// "close_money" => "-" . sprintf("%.2f", ($service_charge * ($entrust_ratio_detail->ratio / 100))),
"close_money" => "-{$entrust_service_charge}",
"close_status" => $order['status'] == 4 ? 3 : 4,
"close_number" => !empty($close_serial_number) ? $close_serial_number : "-",
];
}
// foreach($order_detail as $val){
// $entrust_user = OrderUser::where('batchcode', $order['batchcode'])->where('islicode', $val['entrust_islicode'])->value('name');
// $platform_service_charge += $val['service_charge'];
// $result[] = [
// "close_side" => $entrust_user,
// "close_message" => "标的价款",
// "money" => "+".(sprintf("%.2f", $val['money'] - $val['service_charge'])),
// "tax_rate" => "-",
// "tax_rate_money" => "-",
// "close_money" => "-",
// "close_status" => $order['status'] == 4 ? 3 : 4,
// "close_number" => !empty($order['close_serial_number']) ? $order['close_serial_number'] : "-"
// ];
// $result[] = [
// "close_side" => $entrust_user,
// "close_message" => "交易佣金",
// "money" => "-".(),
// "tax_rate" => "6%",
// "tax_rate_money" => "-",
// "close_money" => "-{$val['service_charge']}",
// "close_status" => $order['status'] == 4 ? 3 : 4,
// "close_number" => !empty($order['close_serial_number']) ? $order['close_serial_number'] : "-"
// ];
// }
$result[] = [
"close_side" => "交易平台",
"close_message" => "交易佣金",
"money" => "+" . sprintf("%.2f", $platform_service_charge),
"tax_rate" => "6%",
"tax_rate_money" => "-",
"close_money" => "+" . sprintf("%.2f", $platform_service_charge),
"close_status" => $order['status'] == 4 ? 3 : 4,
"close_number" => "-",
];
return $result;
}
public function orderCloseCallback($data){
header('content-type:application/json;charset=utf8');
$json = json_decode($data, true);
// dd($json);
$openapiurl="https://t.masget.com/openapi/rest";
// $openapiurl="https://vip12.masget.com:7373/openapi/rest";
// $session = "iba3t9dqln8etmcaceq1xtqr7urevia1";
// $appid="910000198";
// $secretkey="gRAZZKiNw0UbTuF9";
$session = "pw0jhuuijprkk07iyvjmzivf55s2c1cf";
$appid="910000202";
$secretkey="2J8h5c0Nq9wjAEcz";
// $session = "mpcfhx9jw3ap4411sya0t44ymi5r8hun";
// $appid="333320000000803";
// $secretkey="BlyITMWTfOBgpyQD";
// $session = "ub11y2pgvuqzvzp5gwyfqm267ge5ul3b";
// $appid="333320000000800";
// $secretkey="rtTNVC46eLIvcGBt";
$api=new ApiHelperoneService();
$api->init($openapiurl,$appid,$session,$secretkey);
$security = new security();
$decrypted = $security->decrypt($GLOBALS['token_secretkey'], $GLOBALS['token_secretkey'], $json['Data']);
$pattern = "/\\x00/";
$decrypted = preg_replace($pattern, "", $decrypted);
$result = json_decode($decrypted, true);
$ordernumber = $result['ordernumber'];
$batchcode = OrderGoodsDetail::where('close_id', $ordernumber)->where('is_deleted', 0)->value('batchcode');
$this->orderlog->info("{$batchcode}订单结算回调", $result);
$close_number = $result['payorderid'];
$close_status = 0;
if($result['status'] == 4){
$close_status = 5;
}elseif($result['status'] == 1 || $result['status'] == 2 || $result['status'] == 3){
$close_status = 2;
}elseif($result['status'] == 5 || $result['status'] == 6){
$close_status = 4;
}else{
$close_status = 4;
}
$update = [
"close_status" => $close_status,
"close_serial_number" => $close_number,
"callback_msg" => isset($result['respmsg']) ? $result['respmsg'] : '-'
];
// if($close_status == 5){
// $update['status'] = 4;
// }
// Order::where('batchcode', $batchcode)->update($update);
OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)->where('close_id', $ordernumber)->update($update);
if(!OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)->where('close_status', '<', 5)->value('id')){
$completetime = date('Y-m-d H:i:s', strtotime($result['processtime']));
Order::where('batchcode', $batchcode)->update(['status' => 4, "closetime" => $completetime, 'completetime' => $completetime]);
}
}
public function getOrderImageStatus($image, $id){
$image_headers = get_headers($image);
if(!strpos($image_headers[0], "200")){
$path = env("app.real_url") . "/dist/api/v2/preview?url={$image}";
$sign = parent::createSign("distribute");
$headers = array(
CURLOPT_HTTPHEADER => array(
"dist_token:{$sign}",
"Content-Type: application/json"
)
);
//todo 请求如果资源预览地址过期,可通过接口重新获取资源预览地址接口 接口3.4
$res = Http::get($path, [], $headers);
if($res['code'] != 200){
throw new \think\Exception($res['msg'], 400);
}
$res = json_decode($res['data'], true);
if($res['resultCode'] != "00000000"){
throw new \think\Exception($res['resultMsg'], 400);
}
OrderGoodsDetail::where('id', $id)->where('is_deleted', 0)->update(['goods_image' => $res['data']]);
return $res['data'];
}
return $image;
}
public function serviceInvoiceList($invoice_number, $seller, $buy, $batchcode, $status, $createtime, $ticketstatus, $page = 1, $limit = 20){
$pdf_path = (new PayService())->initDir();
$result = (new Ticket())->alias('ticket')->join('order_user user', 'user.batchcode = ticket.batchcode and user.islicode = ticket.islicode')
->join('order order', 'order.batchcode = ticket.batchcode')
->field('order.status,user.name,ticket.id,ticket.pdfUrl,user.uscc,ticket.tickettime,ticket.ticketid,ticket.batchcode,ticket.ticket_status,ticket.ticketimage,ticket.ticketurl,ticket.ticketmoney,ticket.islicode,ticket.ticketApiMessage')
->where(function ($query) use($invoice_number, $seller, $buy, $batchcode, $status, $createtime, $ticketstatus){
if(!empty($invoice_number)){
$query->whereLike('ticket.ticketid', "%{$invoice_number}%");
}
if(!empty($buy)){
$query->whereLike('user.name', "%{$buy}%", 'or')->whereLike("ticket.islicode", "%{$buy}%", "or");
}
if(!empty($batchcode)){
$query->where('ticket.batchcode', $batchcode);
}
if(!empty($status)){
$query->where('order.status', $status);
}
if(!empty($createtime)){
if (isset($createtime[1]) && preg_match("/^\d{4}-\d{2}-\d{2}$/", $createtime[1])){
$createtime[1] = $createtime[1] . ' 23:59:59';
}
if (isset($createtime[0]) && isset($createtime[1]) && $createtime[0] && $createtime[1]){
$query->whereBetweenTime('ticket.tickettime', $createtime[0], $createtime[1]);
}elseif (isset($createtime[0]) && $createtime[0]){
$query->whereTime('ticket.tickettime', '>=', $createtime[0]);
}elseif (isset($createtime[1]) && $createtime[1]){
$query->whereTime('ticket.tickettime', '<=', $createtime[1]);
}
}
if(!empty($ticketstatus)){
$query->where('ticket.ticket_status', $ticketstatus);
}
})->order('ticket.tickettime', 'desc')->paginate($limit)
->each(function ($item) use($pdf_path){
if(empty($item['ticketurl']) && !empty($item['pdfUrl'])){
$status = get_headers($item['pdfUrl']);
$ticketurl = "";
if(strpos($status[0], "200")) {
$pdf_content = file_get_contents($item['pdfUrl']);
file_put_contents('./' . $pdf_path . "{$item['ticketid']}.pdf", $pdf_content);
$ticketurl = $pdf_path . "{$item['ticketid']}.pdf";
}
if($ticketurl){
Ticket::where('id', $item['id'])->update(['ticketurl' => $ticketurl]);
$item['pdfUrl'] = env('app.host') . $ticketurl;
}
}
if(!empty($item['ticketurl'])){
$item['pdfUrl'] = env('app.host') . $item['ticketurl'];
}
$item['seller_name'] = "深圳文化产权交易所有限公司";
$item['seller_number'] = "91440300553866701D";
return $item;
});
$result = $result->toArray();
$start = ($page - 1) * $limit + 1;
$end = $page * $limit;
if($result['total'] < $end){
$end = $result['total'];
}
if($result['total'] < $start){
$start = $end = $result['total'];
}
$result['start'] = $start;
$result['end'] = $end;
return $result;
}
public function downloadInvoice($id){
$ticket = Ticket::where('id', $id)->find();
if($ticket){
if(empty($ticket['ticketurl'])){
throw new \think\Exception("未获取到链接", 400);
}
return download('.' . $ticket['ticketurl'], $ticket['ticketid']);
}
}
public function getBill($batchcode){
$pdf_path = (new PayService())->initDir();
return Ticket::where('batchcode', $batchcode)->field('id,ticketurl,pdfUrl,ticketid')->select()->each(function ($item) use($pdf_path){
if(empty($item['ticketurl']) && !empty($item['pdfUrl'])){
$status = get_headers($item['pdfUrl']);
$ticketurl = "";
if(strpos($status[0], "200")) {
$pdf_content = file_get_contents($item['pdfUrl']);
file_put_contents('./' . $pdf_path . "{$item['ticketid']}.pdf", $pdf_content);
$ticketurl = $pdf_path . "{$item['ticketid']}.pdf";
}
if($ticketurl){
Ticket::where('id', $item['id'])->update(['ticketurl' => $ticketurl]);
$item['pdfUrl'] = env('app.host') . $ticketurl;
}
}
if(!empty($item['ticketurl'])){
$item['pdfUrl'] = env('app.host') . $item['ticketurl'];
}
return $item;
})->toArray();
}
public function createOrderClose($user_isli, $batchcode, $payee_name, $payee_bank, $payee_account, $order){
$result = (new SeparateAccountService())->getBankCode($payee_bank, $payee_account);
if($result['ret'] != 0){
throw new \think\Exception("获取联行号失败", 400);
}
$bankcode = $result['data']['rows']['0']['bankcode'];
if(empty($bankcode)){
throw new \think\Exception("获取联行号失败", 400);
}
$ratio_detail = AccountRatioDetail::where('setting_id', $order->account_ratio_id)->where('role_type', 1)->find();
$order_detail = OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)->where('entrust_islicode', $user_isli)->select()->toArray();
$account = [];
$total_money = 0;
foreach($order_detail as $value){
if(in_array($value['entrust_islicode'], $account)){
$user_money = $account[$value['entrust_islicode']]['txnamount'];
if($ratio_detail->calculate == 1){
if($ratio_detail->ratio <= 0){
$money = round($value['goods_price'], 2) * 100;
}else{
$money = round($value['goods_price'] * ($ratio_detail->ratio / 100), 2) * 100;
}
}else{
$money = round(($value['goods_price'] - $ratio_detail->amount), 2) * 100;
}
if($money <= 0){
OrderGoodsDetail::where('id', $value['id'])->update(['close_status' => 5, 'is_close' => 1]);
continue;
}
$total_money += $money;
$user_money = $user_money + $money;
$account[ $value['entrust_islicode'] ]['txnamount'] = $user_money;
}else{
if($ratio_detail->calculate == 1){
if($ratio_detail->ratio <= 0){
$money = round($value['goods_price'], 2) * 100;
}else{
$money = round($value['goods_price'] * ($ratio_detail->ratio / 100), 2) * 100;
}
}else{
$money = round(($value['goods_price'] - $ratio_detail->amount), 2) * 100;
}
if($money <= 0){
OrderGoodsDetail::where('id', $value['id'])->update(['close_status' => 5, 'is_close' => 1]);
continue;
}
$entrust_userinfo = OrderUser::where('id', $value['user_id'])->find();
$total_money += $money;
$order_id = md5(time() . $value['id'] . uniqid());
OrderGoodsDetail::where('batchcode', $value['batchcode'])->where('is_deleted', 0)->where('entrust_islicode', $value['entrust_islicode'])->update(['close_id' => $order_id]);
$account[ $value['entrust_islicode'] ] = [
"ordernumber" => $order_id,
"accountname" => $entrust_userinfo['bankAccountName'],
"bankaccount" => $payee_account,
"accounttype" => 0,
"bankcode" => $bankcode,
"bank" => $payee_bank,
"txnamount" => $money,
];
}
}
if((!$order_detail || $total_money <= 0) && !OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)->where('close_status', '<', 5)->value('id')){
OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)->where('entrust_islicode', $user_isli)->update(['close_status' => 5, 'is_close' => 1]);
return ['close_status' => 5];
}
$batchnumber = md5(uniqid() . time() . rand(1000, 9999));
$account = array_values($account);
$this->orderlog->info("{$batchcode}发起代付", $account);
$result = (new SeparateAccountService())->StartSplitting($account, $total_money, $batchnumber);
$this->orderlog->info("{$batchcode}发起代付结果", $result);
$close_status = 4;
if($result['ret'] == 0){
OrderUser::where('batchcode', $batchcode)->where('islicode', $user_isli)->update(['publicAccount' => $payee_account, 'bankName' => $payee_bank]);
$close_status = 2;
}
OrderGoodsDetail::where('batchcode', $batchcode)->where('is_deleted', 0)->where('entrust_islicode', $user_isli)->update(['close_status' => $close_status, 'is_close' => 1, 'callback_msg' => $result['message']]);
return ['close_status' => $close_status];
}
}