cxgj/modules/api/models/OrderGoodsForm.php
2023-11-27 09:45:13 +08:00

660 lines
25 KiB
PHP

<?php
/**
* @author Any
* @description KISS
* @date 2020-12-2
* @version 1.0.0
*
* _____LOG_____
*
*/
namespace app\modules\api\models;
use app\components\YopointApi;
use app\models\DevList;
use app\models\integral\Integral;
use app\models\Level;
use app\models\Model;
use app\components\SiteHelper;
use app\components\SysConst;
use app\models\Goods;
use app\models\GoodsHub;
use app\models\Order;
use app\models\OrderDetail;
use app\models\OrderSale;
use app\models\UniqueOrderNo;
use app\models\User;
use app\modules\api\components\ApiHelper;
use yii\data\Pagination;
use yii\db\Exception;
class OrderGoodsForm extends ApiModel
{
public $cx_mch_id = 0;
public $page; //页数
public $limit;//每页条数
public $user_id;
public $status;//订单状态0=全部1=待支付2=已支付3=退款/取消
public $order_id;//订单ID
public $cid; //设备ID
public $is_commit=true;
public function rules()
{
return [
[['page'], 'default', 'value' => 1],
[['limit'], 'default', 'value' => 10],
[['limit', 'page','user_id','status','order_id'], 'integer'],
[['cid'], 'string'],
['status', 'in', 'range' => array(0,1,2,3)],
[['user_id'], 'required', 'on' => 'order_goods_lists'],
[['user_id','order_id'], 'required', 'on' => 'order_buy_goods_view'],
[['user_id','cid'], 'required', 'on' => 'order_buy_goods'],
// [['user_id'], 'required', 'on' => 'order_goods_check'],
[['user_id','order_id'], 'required', 'on' => 'order_goods_sale_details'],
];
}
public function orderGoodsLists()
{
if (!$this->validate()) {
return $this->getModelError();
}
$query = Order::find()
->select('id,status,created_at,total_goods_price,total_price,pay_time,is_pay')
->where([
'is_delete' => 0,
'user_id' => $this->user_id,
'plugin_sign' => 'goods',
]);
if($this->status == 1){
$query->andWhere(['status' => 1,'is_pay' => 0]);
}elseif ($this->status == 2){
$query->andWhere(['status' => 0,'is_pay' => 1]);
}elseif ($this->status == 3){
$query->andWhere(['status' => [2,3]]);
}
$count = $query->count();
$pagination = new Pagination(['pageSize' => $this->limit, 'totalCount' => $count, 'page' => $this->page - 1]);
$list = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy(['id' => SORT_DESC])->asArray()->all();
$end_flag = $this->page > $pagination->pageCount ? true : false;
$orderSalesTime = SiteHelper::getCustomiseOptionByKey("orderSalesTime", "hump");
foreach ($list as $index => &$item) {
$item['created_at_cn'] = date('Y/m/d H:i',$item['created_at']);
$item['total_goods_price'] = sprintf("%.2f",$item['total_goods_price']);
$item['total_price'] = sprintf("%.2f",$item['total_price']);
$detail = OrderDetail::find()
->where(['is_delete' => 0,'plugin_sign' => 'goods','order_id' => $item['id']])
->select('id,goods_attr_info')->asArray()->all();
$item['count'] = count($detail);
foreach ($detail as $index2 => &$item2){
$item2['goods_attr_info'] = json_decode($item2['goods_attr_info'],true);
}
$goods_attr_infos = array_column($detail,'goods_attr_info');
$cover_pics = array_column($goods_attr_infos,'cover_pic');
$item['cover_pics'] = array_filter($cover_pics);
switch ($item['status'])
{
case 0:
$item['status_cn'] = '已完成';
break;
case 1:
$item['status_cn'] = '待支付';
break;
case 2:
$item['status_cn'] = '已完成';
break;
case 3:
$item['status_cn'] = '已取消';
break;
default:
$item['status_cn'] = '未知';
}
$item['sale_button'] = false;
$time = $item['pay_time'] + ($orderSalesTime * 60);
if($time > time() && $item['total_goods_price'] > 0 && $item['status'] == 0){
$item['sale_button'] = true;
}
}
return [
'code' => 0,
'msg' => 'ok',
'data' => $list,
'count' => $count,
'page' => $this->page,
'limit' => $this->limit,
'page_count' => $pagination->pageCount,
'end_flag' => $end_flag,
];
}
public function orderGoodsCheck()
{
// if (!$this->validate()) {
// return $this->getModelError();
// }
if(empty($this->user_id)){
return [
'code' => 0,
'msg' => 'ok',
'data' => [],
];
}
$redis_name = "cxgyc:YopointNotify:user:{$this->user_id}_lock";
$redis_user_name = "cxgyc:YopointNotify:user:{$this->user_id}";
$get = \Yii::$app->redis->get($redis_user_name);
if(!empty($get) && intval($get) === 2){
return [
'code' => 0,
'msg' => 'ok',
'data' => [],
];
}
$setnx = \Yii::$app->redis->setnx($redis_name,1);
if(empty($setnx)){
$ttl = \Yii::$app->redis->ttl($redis_name);
if($ttl === -1){
\Yii::$app->redis->expire($redis_name,5);
}
return [
'code' => 0,
'msg' => 'ok',
'data' => [],
];
}
\Yii::$app->redis->expire($redis_name,5);
$order = Order::find()
->select('id,created_at')
->where([
'user_id' => $this->user_id,
'is_delete' => 0,
'plugin_sign' => 'goods',
'is_pay' => 0,
'cancel_status' => 0,
])
->orderBy(['id' => SORT_DESC])
->asArray()
->one()??[];
if(empty($order)){
\Yii::$app->redis->setex($redis_user_name,60*60,2);
}else{
\Yii::$app->redis->setex($redis_user_name,60*60,1);
}
return [
'code' => 0,
'msg' => 'ok',
'data' => $order,
];
}
public function orderGoodsDetails()
{
if (!$this->validate()) {
return $this->getModelError();
}
$user = ApiHelper::findOneUser($this->user_id, $this->cx_mch_id);
if ($user == null) {
return [
'code' => 1,
'msg' => '用户不存在'
];
}
$order = Order::findOne(['id' => $this->order_id,'is_delete' => 0]);
if($order == null){
return $this->apiReturnError('订单不存在');
}
//计算待支付时间
$orderTimeoutCancel = SiteHelper::getCustomiseOptionByKey("orderTimeoutCancel", "hump");
$orderTimeoutCancel = $orderTimeoutCancel * 60;
$timeout_cancel = floor(($order->created_at + $orderTimeoutCancel) - time());
$timeout_cancel = $timeout_cancel <= 0 || $order->is_pay == 1 ? 0 : $timeout_cancel;
$timeout_cancel = 0;
// if($timeout_cancel <= 0 && $order->is_pay == 0){
// $order->status = 3;
// $order->cancel_status = 1;
// $order->cancel_time = time();
// $order->updated_at = time();
// if (!$order->save()) {
// return $this->getModelError($order);
// }
// }
$detail = OrderDetail::find()
->select('id,goods_id,num,unit_price as price,total_original_price,total_price,goods_attr_info')
->where([
'order_id' => $order->id,
'is_delete' => 0
])
->asArray()
->all();
if(empty($detail)){
return $this->apiReturnError('订单暂无商品');
}
$discount = 0;
if(\Yii::$app->user->identity->level_id != 0){
$level = Level::findOne(['id' => \Yii::$app->user->identity->level_id]);
$discount = $level == null ? 0 : $level->discount;
}
$transaction = \Yii::$app->db->beginTransaction();
foreach ($detail as $index => &$item){
$goods_attr_info = json_decode($item['goods_attr_info'],true);
if($discount != 0 && $order->is_pay == 0){
$item['total_price'] = sprintf('%.2f', $item['total_original_price'] * ($discount / 100));
}
$goods_attr_info['total_price'] = $item['total_price'];
$goods_attr_info['cover_pic'] = SiteHelper::getFullUrl($goods_attr_info['cover_pic']);
$detail_goods = [
'total_price' => $item['total_price'],
'updated_at' => time(),
'goods_attr_info' => json_encode($goods_attr_info)
];
$r = \Yii::$app->db->createCommand()->update(OrderDetail::tableName(),$detail_goods, ['id' => $item['id']])->execute();
if(!$r){
$transaction->rollBack();
return $this->apiReturnError('订单商品异常');
}
$item['cover_pic'] = $goods_attr_info['cover_pic'];
$item['name'] = $goods_attr_info['name'];
$item['unit'] = $goods_attr_info['unit'];
}
$account_integral = empty($user->integral) ? 0 : $user->integral->account_integral;
$account_integral = substr(sprintf("%.3f",$account_integral),0,-1);
if($order->is_pay == 0){
//订单原价
$total_price = array_sum(array_column($detail,'total_original_price'));
$total_price = sprintf('%.2f', $total_price);
//计算出需要支付的现金部分
if($account_integral >= $total_price){
// $total_price_subtract_int = $account_integral - $total_price;
$total_price_subtract_int = 0;
$integral = $total_price;//抵扣积分
}else{
$total_price_subtract_int = sprintf('%.2f', $total_price - $account_integral); //总计价格
$integral = $account_integral; //抵扣积分
}
if($total_price_subtract_int > 0 && $discount > 0){
$total_price_subtract_int = sprintf('%.2f', $total_price_subtract_int * ($discount / 100));
$order->total_pay_price = $total_price_subtract_int;
$order->total_goods_price = $total_price_subtract_int;
$order->integral = $integral;
$order->member_discount = $discount;
$order->updated_at = time();
if(!$order->save()){
$transaction->rollBack();
return $this->apiReturnError('订单异常');
}
}
}
$orderSalesTime = SiteHelper::getCustomiseOptionByKey("orderSalesTime", "hump");
$sale_button = false;
$time = $order->pay_time + ($orderSalesTime * 60);
if($time > time() && $order->total_goods_price > 0 && $order->status == 0){
$sale_button = true;
}
if($order->member_discount > 0){
$order->member_discount = 100 - $order->member_discount;
}
$data = [
'id' => $order->id,
'order_no' => $order->order_no,
'status' => $order->status,//1=未支付0=已支付
'pay_type' => $order->pay_type,//0=余额支付1=微信支付
'created_at' => $order->created_at,
'created_at_cn' => date('Y/m/d H:i:s',$order->created_at),
'total_price' => sprintf("%.2f",$order->total_price),//总计
'discount' => $order->member_discount.'%',
'integral' => sprintf("%.2f",$order->integral),//抵扣积分
'sure_price' => sprintf("%.2f",$order->total_goods_price),//总计价格
'account_integral' => sprintf("%.2f",$account_integral),
'detail' => $detail,
'timeout_cancel' => $timeout_cancel,
'plugin_sign' => $order->plugin_sign,
'sale_button' => $sale_button,
'discount_money' => sprintf("%.2f",$order->total_price-$order->integral-$order->total_goods_price), # 会员折扣
];
$transaction->commit();
return $this->apiReturnSuccess('ok',$data);
}
public function addGoodsOrder()
{
if (!$this->validate()) {
return $this->getModelError();
}
$exists = Order::find()->where(['user_id' => $this->user_id,'status' => 1,'plugin_sign' => 'goods','is_delete'=>0])->exists();
if($exists){
return $this->apiReturnError('存在未完成订单,请先处理');
}
$dev = DevList::findOne(['dev_id' => $this->cid]);
if ($dev == null) {
return $this->apiReturnError('设备异常');
}
if ($dev->store_id == 0) {
return $this->apiReturnError('设备未绑定门店');
}
// 判断设备状态
$find_order = Order::find()->andWhere([
'dev_id' => $dev->id,
'is_delete' => [0,1],
'status' => 1,
'plugin_sign' => 'goods',
'is_recycle' => 0,
])->exists();
if($find_order){
return $this->apiReturnError('设备正在进行中');
}
// 判断设备状态
/*$find_order = Order::find()->andWhere([
'dev_id' => $dev->id,
'is_delete' => [0,1],
'status' => 1,
'plugin_sign' => 'goods',
'is_recycle' => 1,
'user_id' => $this->user_id,
])->exists();
if($find_order){
return $this->apiReturnError('设备正在进行中');
}*/
$level = Level::findOne(['id' => \Yii::$app->user->identity->level_id]);
if($level == null){
$member_discount = '0%';
}else{
$member_discount = $level->discount.'%';
}
$t = \Yii::$app->db->beginTransaction();
$mobile = \Yii::$app->user->identity->mobile_phone;
$obj = new YopointApi();
$obj->user_id = $this->user_id;
//订单类型
$orderType = UniqueOrderNo::ORDER_TYPE_GOODS;
$order_no = UniqueOrderNo::generate($orderType, Order::class, 24, 1, 3, 'order_no');
$yp = $obj->openDev($this->cid, $order_no, $mobile);
if (empty($yp)) {
$t->rollBack();
return $this->apiReturnError('接口异常');
}
if (empty($yp['data'])) {
$t->rollBack();
return $this->apiReturnError($yp['error_msg']);
}
// 查找订单号
$order = Order::find()->where(['user_id' => $this->user_id,'status' => 1,'plugin_sign' => 'goods','is_delete'=>1,'yopoint_order'=>$yp['data']['ReceiptNo']])->one();
if(empty($order)){
$order = new Order();
$order->cx_mch_id = 0;
$order->user_id = $this->user_id;
$order->order_no = UniqueOrderNo::generate($orderType, Order::class, 24, 1, 3, 'order_no');
$order->express_price = 0;
$order->express_original_price = 0;
$order->total_goods_price = 0;
$order->total_goods_original_price = 0;
$order->use_user_coupon_id = 0;
$order->coupon_discount_price = 0;
$order->is_pay = 0;
$order->pay_type = SysConst::$cxPayTypeBalance;
$order->store_id = $dev->store_id;
$order->plugin_sign = 'goods';
$order->created_at = time();
$order->total_price = 0; //总金额
$order->total_pay_price = 0;
$order->dev_id = $dev->id;
$order->is_delete = 1;
$order->yopoint_status = 0;
$order->member_discount = $member_discount;
$order->yopoint_order = $yp['data']['ReceiptNo'];
$order->yopoint_notify_id = $yp['log_id'];
if (!$order->save()) {
$t->rollBack();
$msg = $this->getModelError($order);
return $this->apiReturnError('创建订单错误-' . $msg['msg']);
}
}
$t->commit();
return $this->apiReturnSuccess('ok',['id' => $order->id]);
}
//浏览商品订单
public function orderBuyGoodsView()
{
/*if (!$this->validate()) {
return $this->getModelError();
}*/
// $exists = Order::find()
// ->where(['is_delete'=>0,'user_id' => $this->user_id,'status' => 1])
// ->andWhere(['!=','id',$this->order_id])
// ->exists();
// if($exists){
// return $this->apiReturnError('存在未完成订单,请先处理');
// }
$user = ApiHelper::findOneUser($this->user_id, $this->cx_mch_id);
if ($user == null) {
return [
'code' => 1,
'msg' => '用户不存在'
];
}
$order = Order::findOne(['id' => $this->order_id,'user_id' => $this->user_id]);
if($order == null){
return $this->apiReturnError('订单不存在');
}
//折扣百分比
$discount = 0;
$user_info = User::findOne([
'id' => $this->user_id,
]);
if(!empty($user_info->level_id)){
$level = Level::findOne(['id' => $user_info->level_id]);
if($level != null){
$discount = $level->discount;
}
}
$detail = OrderDetail::find()->alias('od')
->select('od.id,od.goods_id,od.num,gh.name,g.price,gh.unit,gh.cover_pic')
->leftJoin(['g' => Goods::tableName()],'od.goods_id=g.id')
->leftJoin(['gh' => GoodsHub::tableName()],'g.goods_hub_id=gh.id')
->where(['od.order_id' => $order->id,'od.is_delete' => 0])
->asArray()->all();
if(empty($detail)){
return $this->apiReturnError('订单暂无商品');
}
//计算待支付时间
$orderTimeoutCancel = SiteHelper::getCustomiseOptionByKey("orderTimeoutCancel", "hump");
$orderTimeoutCancel = $orderTimeoutCancel * 60;
$timeout_cancel = floor(($order->created_at + $orderTimeoutCancel) - time());
$timeout_cancel = $timeout_cancel <= 0 ? 0 : $timeout_cancel;
$timeout_cancel = 0;
if(empty($this->is_commit)){
$transaction = \Yii::$app->db->beginTransaction();
}
foreach ($detail as $index => &$item){
$item['cover_pic'] = SiteHelper::getFullUrl($item['cover_pic']);
$item['total_original_price'] = sprintf('%.2f', $item['price'] * $item['num']);
if($discount != 0){
$item['total_price'] = sprintf('%.2f', $item['total_original_price'] * ($discount / 100));
}else{
$item['total_price'] = $item['total_original_price'];
}
$item['total_original_price'] = sprintf("%.2f",$item['total_original_price']);
$item['total_price'] = sprintf("%.2f",$item['total_price']);
$detail_goods = [
'unit_price' => $item['price'],
'total_original_price' => $item['total_original_price'],
'total_price' => $item['total_price'],
'updated_at' => time(),
'plugin_sign' => 'goods',
'goods_attr_info' => json_encode($item)
];
$r = \Yii::$app->db->createCommand()->update(OrderDetail::tableName(),$detail_goods, ['id' => $item['id']])->execute();
if(!$r){
if(empty($this->is_commit)) {
$transaction->rollBack();
}
return $this->apiReturnError('订单商品异常');
}
}
//订单原价
$total_price = array_sum(array_column($detail,'total_original_price'));
$total_price = sprintf('%.2f', $total_price);
//账户积分
$account_integral = empty($user->integral) ? 0 : $user->integral->account_integral;
$account_integral = substr(sprintf("%.3f",$account_integral),0,-1);
//计算出需要支付的现金部分
if($account_integral >= $total_price){
$total_price_subtract_int = 0;
$integral = $total_price;//抵扣积分
}else{
$total_price_subtract_int = sprintf('%.2f', $total_price - $account_integral); //总计价格
$integral = $account_integral; //抵扣积分
}
if($total_price_subtract_int > 0 && $discount > 0){
$total_price_subtract_int = sprintf('%.2f', $total_price_subtract_int * ($discount / 100));
}
//会员价算
// if($account_integral >= $sure_price){
// // $sure_price = 0;//总计价格
// $sure_price = $account_integral - $sure_price;
// $integral = $sure_price;//抵扣积分
// }else{
// //账户积分<会员价
// $sure_price = sprintf('%.2f', $sure_price - $account_integral); //总计价格
// $integral = $account_integral; //抵扣积分
// }
$discount2 = 0;
if($discount > 0){
$discount2 = 100 - $discount;
}
$data = [
'id' => $order->id,
'order_no' => $order->order_no,
'status' => $order->status,//1=未支付0=已支付
'pay_type' => $order->pay_type,//0=余额支付1=微信支付
'created_at' => $order->created_at,
'created_at_cn' => date('Y/m/d H:i:s',$order->created_at),
'total_price' => sprintf("%.2f",$total_price),//总计
'discount' => $discount2.'%',
'integral' => sprintf("%.2f",$integral),//抵扣积分
// 'sure_price' => $sure_price,//总计价格
'sure_price' => sprintf("%.2f",$total_price_subtract_int),//总计价格
'account_integral' => substr(sprintf("%.3f",$account_integral),0,-1),
'detail' => $detail,
'timeout_cancel' => $timeout_cancel,
'discount_money' => sprintf("%.2f",$total_price-$integral-$total_price_subtract_int), # 会员折扣
];
$order->total_price = $total_price;
$order->total_pay_price = $total_price_subtract_int;
$order->total_goods_price = $total_price_subtract_int;
$order->integral = $integral;
$order->member_discount = $discount;
if(!$order->save()){
if(empty($this->is_commit)) {
$transaction->rollBack();
}
return $this->apiReturnError('订单异常');
}
// if(!empty($order->integral) && $order->plugin_sign == 'goods'){
// $desc = '商品下单抵扣';
// $order_type = UniqueOrderNo::getOrderTypeByOrderNo($order->order_no);
// $r = Integral::userIntegralWalletLog($order->user_id,Integral::TYPE_PAY,$order->integral,$desc,$order_type,$order->order_no);
// if(!$r){
// $transaction->rollBack();
// return Model::asReturnError("订单积分异常");
// }
// }
if(empty($this->is_commit)) {
$transaction->commit();
}
$redis_user_name = "cxgyc:YopointNotify:user:{$this->user_id}";
\Yii::$app->redis->setex($redis_user_name,60*5,2);
return $this->apiReturnSuccess('ok',$data);
}
public function orderGoodsSaleDetails()
{
if (!$this->validate()) {
return $this->getModelError();
}
$order = Order::findOne(['id' => $this->order_id,'user_id' => $this->user_id,'is_delete' => 0]);
if($order == null){
return $this->apiReturnError('订单异常');
}
$sale = OrderSale::find()
->where([
'order_id' => $order->id,
'user_id' => $order->user_id,
'is_delete' => 0
])
->orderBy(['id' => SORT_DESC])
->one();
if($sale == null){
return $this->apiReturnError('订单售后异常');
}
$data = [
'type' => $sale->type,
'status' => $sale->status,
'refund_price' => $sale->refund_price,
'pay_type' => $order->pay_type,
'merchant_remark' => $sale->merchant_remark,
];
if(empty($data['merchant_remark'])){
if($data['status'] == 1){
$data['merchant_remark'] = '您已申请退款,请耐心等待。';
}elseif ($data['status'] == 2){
$data['merchant_remark'] = '您的订单正在退款,请耐心等待。';
}elseif ($data['status'] == 3){
$data['merchant_remark'] = '您的退款申请,已被拒绝。';
}elseif ($data['status'] == 4){
$data['merchant_remark'] = '您的订单已成功退款,预计1-3个工作日到账,请耐心等待。';
}
}
return $this->apiReturnSuccess('ok',$data);
}
}