canyin-project/ybcy/models/common/Order.php
2024-11-01 16:07:54 +08:00

1801 lines
74 KiB
PHP
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* 云贝餐饮连锁V2版权说明
******************************************************************
《云贝餐饮连锁V2》是武汉云贝网络科技有限公司历经2余年时间独立创作开发而成且在不断的进行升级开发中《云贝餐饮连锁V2 》的源代码、布局、界面设计、电子文档等均已提交国家版权局登记备案,并已获得著作权审批 和销售许可 (软著登字第 6839058号 登记号 2021SR0114741
官方网址为www.b-ke.cn
官方联系方式153-0719-3890王经理
******************************************************************
注意:本软件非开源系统,版权归武汉云贝网络科技有限公司依法所有,并受到法律的严格保护;未经过我司授权,不得擅自二开、破解、倒卖等任何的侵权、盗版行为均将追究其法律责任。
*/
namespace app\models\common;
use app\models\common\Voice;
use Yii;
use yii\db\ActiveRecord;
use app\models\common\Config;
use app\models\baidu\AipSpeech;
use app\models\common\CallbackOrder;
use app\models\common\Ali;
use app\models\common\Delivery;
use app\models\common\WeChat;
use app\models\common\Bill;
use app\models\common\Message;
use app\models\common\Printing;
use app\models\common\Member;
use app\controllers\common\FuiouController;
class Order extends ActiveRecord{
//计算配送时间
public static function getDeliveryTime($startLat,$startLng,$storeId){
$store=(new \yii\db\Query())
->from('{{%ybwm_store}}')
->where('id=:id',[':id'=>$storeId])->one();
$distance=getDistance($startLat,$startLng,$store['lat'],$store['lng']);
$storeSet=Config::getStoreSet('delivery',$storeId);
if($distance<=3){
return $storeSet['withinTime'];
}
return bcadd(bcmul(intval($distance-3),$storeSet['exceedTime'],0),$storeSet['withinTime'],0)?:30;
}
/**productionTime
* @param $point
* @param $circle
* @return bool
*cancel
* 判断一个坐标是否在圆内
* 思路:判断此点的经纬度到圆心的距离 然后和半径做比较
* 如果此点刚好在圆上 则返回true
* @param $point ['lng'=>'','lat'=>''] array指定点的坐标
* @param $circle array ['center'=>['lng'=>'','lat'=>''],'radius'=>''] 中心点和半径
*/
static function is_point_in_circle($point, $circle) {
$distance = self::distance($point['lat'], $point['lng'], $circle['center']['lat'], $circle['center']['lng']);
if ($distance <= $circle['radius']) {
return true;
} else {
return false;
}
}
/**
* 计算两个点之间的距离
* @param $latA [第一个点的纬度]
* @param $lonA [第一个点的经度]
* @param $latB [第二个点的纬度]
* @param $lonB [第二个点的经度]
* @return float
*/
static function distance($latA, $lonA, $latB, $lonB) {
$earthR = 6371000.;
$PI = 3.14159265358979324;
$x = cos($latA * $PI / 180.) * cos($latB * $PI / 180.) * cos(($lonA - $lonB) * $PI / 180);
$y = sin($latA * $PI / 180.) * sin($latB * $PI / 180.);
$s = $x + $y;
if ($s > 1) {
$s = 1;
}
if ($s < -1) {
$s = -1;
}
$alpha = acos($s);
$distance = $alpha * $earthR;
return $distance;
}
/**
* * 判断一个坐标是否在一个多边形内(由多个坐标围成的)
* 基本思想是利用射线法,计算射线与多边形各边的交点,如果是偶数,则点在多边形外,否则
* 在多边形内。还会考虑一些特殊情况,如点在多边形顶点上,点在多边形边上等特殊情况。
* @param $point
* @param $pts
* @return bool
* @param $point [指定点坐标]
* @param $pts [多边形坐标 顺时针方向]
*/
static function is_point_in_polygon($point, $pts) {
$N = count($pts);
$boundOrVertex = true; //如果点位于多边形的顶点或边上也算做点在多边形内直接返回true
$intersectCount = 0; //cross points count of x
$precision = 2e-10; //浮点类型计算时候与0比较时候的容差
$p1 = 0; //neighbour bound vertices
$p2 = 0;
$p = $point;
$p1 = $pts[0];
for ($i = 1; $i <= $N; ++$i) {
if ($p['lng'] == $p1['lng'] && $p['lat'] == $p1['lat']) {
return $boundOrVertex; //p is an vertex
}
$p2 = $pts[$i % $N]; //right vertex
if ($p['lat'] < min($p1['lat'], $p2['lat']) || $p['lat'] > max($p1['lat'], $p2['lat'])) {
$p1 = $p2;
continue; //next ray left point
}
if ($p['lat'] > min($p1['lat'], $p2['lat']) && $p['lat'] < max($p1['lat'], $p2['lat'])) {
if ($p['lng'] <= max($p1['lng'], $p2['lng'])) {
if ($p1['lat'] == $p2['lat'] && $p['lng'] >= min($p1['lng'], $p2['lng'])) {
return $boundOrVertex;
}
if ($p1['lng'] == $p2['lng']) {
if ($p1['lng'] == $p['lng']) {
return $boundOrVertex;
} else {
++$intersectCount;
}
} else {
$xinters = ($p['lat'] - $p1['lat']) * ($p2['lng'] - $p1['lng']) / ($p2['lat'] - $p1['lat']) + $p1['lng'];
if (abs($p['lng'] - $xinters) < $precision) {
return $boundOrVertex;
}
if ($p['lng'] < $xinters) {
++$intersectCount;
}
}
}
} else {
if ($p['lat'] == $p2['lat'] && $p['lng'] <= $p2['lng']) {
$p3 = $pts[($i + 1) % $N]; //next vertex
if ($p['lat'] >= min($p1['lat'], $p3['lat']) && $p['lat'] <= max($p1['lat'], $p3['lat'])) {
++$intersectCount;
} else {
$intersectCount += 2;
}
}
}
$p1 = $p2;
}
if ($intersectCount % 2 == 0) {
//偶数在多边形外
return false;
} else {
//奇数在多边形内
return true;
}
}
//计算配送费(按区域)
public static function getAreaDeliveryMoney($startLat,$startLng,$storeId){
$store=Config::getStoreSet('delivery',$storeId);
if (!$store['areaArr']) {
$data['money'] = 0;
$data['startMoney'] = 0;
return $data;
}
$delivery = $store['areaArr'];
$ages = array();
foreach ($delivery as $user) {
$ages[] = $user['money'];
}
array_multisort($ages, SORT_ASC, $delivery);
$point = ['lng' => $startLng, 'lat' => $startLat];
for ($i = 0; $i < count($delivery); $i++) {
if ($delivery[$i]['shape'] == 1) {
$circle = [
'center' => ['lng' => $delivery[$i]['lng'], 'lat' => $delivery[$i]['lat']],
'radius' => $delivery[$i]['radius'],
];
$res = self::is_point_in_circle($point, $circle);
if ($res) {
$data['startMoney'] = $delivery[$i]['startMoney'];
$timeArr=$delivery[$i]['timeArr'];
if($timeArr){
for($j=0;$j<count($timeArr);$j++){
$startTime=strtotime(date("Y-m-d ".$timeArr[$j]['startTime']));
$endTime=strtotime(date("Y-m-d ".$timeArr[$j]['endTime']));
if(time()>=$startTime AND time()<=$endTime){
$data['money']=bcadd($delivery[$i]['money'],$timeArr[$j]['money'],2);
break;
}
}
}else{
$data['money']=$delivery[$i]['money'];
}
return $data;
break;
}
}
if ($delivery[$i]['shape'] == 2) {
$pts = [];
for ($k = 0; $k < count($delivery[$i]['details']); $k++) {
$pts[] = ['lng' => $delivery[$i]['details'][$k]['lng'], 'lat' => $delivery[$i]['details'][$k]['lat']];
}
$res = self::is_point_in_polygon($point, $pts);
if ($res) {
$data['startMoney'] = $delivery[$i]['startMoney'];
$timeArr=$delivery[$i]['timeArr'];
if($timeArr){
for($j=0;$j<count($timeArr);$j++){
$startTime=strtotime(date("Y-m-d ".$timeArr[$j]['startTime']));
$endTime=strtotime(date("Y-m-d ".$timeArr[$j]['endTime']));
if(time()>=$startTime AND time()<=$endTime){
$data['money']=bcadd($delivery[$i]['money'],$timeArr[$j]['money'],2);
break;
}
}
}else{
$data['money']= $delivery[$i]['money'];
}
return $data;
break;
}
}
}
return false;
}
//计算配送费(按距离)
public static function getDistanceDeliveryMoney($startLat,$startLng,$storeId){
$store=Config::getStoreSet('delivery',$storeId);
$data['startMoney']=$store['startMoney'];
$storeInfo=(new \yii\db\Query())
->from('{{%ybwm_store}}')
->where('id=:id',[':id'=>$storeId])->one();
$system=Config::getSystemSet('system',$storeInfo['uniacid']);
$timeArr=$store['timeArr'];
if($store['calculationType']==2){
$from = $startLat . "," . $startLng;
$to = $storeInfo['lat'] . "," . $storeInfo['lng'];
//骑行距离
$url="https://apis.map.qq.com/ws/distance/v1/matrix?mode=bicycling&from=".$from."&to=".$to."&key=".$system['txKey'];
// echo $url;die;
$res=httpRequest($url);
// print_R($res);die;
$distance=json_decode($res,true)['result']['rows'][0]['elements'][0]['distance'];
$distance=bcdiv($distance,1000,1);
}else{
$distance=getDistance($startLat,$startLng,$storeInfo['lat'],$storeInfo['lng']);
}
if($distance<=$store['startDistance']){
$data['money']=$store['distanceStartMoney'];
for($i=0;$i<count($timeArr);$i++){
$startTime=strtotime(date("Y-m-d ".$timeArr[$i]['startTime']));
$endTime=strtotime(date("Y-m-d ".$timeArr[$i]['endTime']));
if(time()>=$startTime AND time()<=$endTime){
$data['money']=bcadd($data['money'],$timeArr[$i]['money'],2);
break;
}
}
return $data;
}
if($distance>$store['startDistance'] AND $distance<=$store['overstepDistance']){
//超过起步公里 并且小于超出公里
$deliveryMoney=$store['distanceStartMoney']+($distance-$store['startDistance'])*$store['overstepMoney'];
}
if($distance>$store['startDistance'] AND $distance>$store['overstepDistance']){
//超过起步公里 并且大于超出公里
$deliveryMoney=$store['distanceStartMoney']+($distance-$store['startDistance'])*$store['overstepDistanceMoney'];
}
$data['money']=$deliveryMoney>$store['maxMoney']?$store['maxMoney']:$deliveryMoney;
for($i=0;$i<count($timeArr);$i++){
$startTime=strtotime(date("Y-m-d ".$timeArr[$i]['startTime']));
$endTime=strtotime(date("Y-m-d ".$timeArr[$i]['endTime']));
if(time()>=$startTime AND time()<=$endTime){
$data['money']=bcadd($data['money'],$timeArr[$i]['money'],2);
break;
}
}
return $data;
}
//计算配送费
public static function getDeliveryMoney($startLat,$startLng,$storeId,$orderMoney=0){
$userId=Yii::$app->request->headers->get('userId');
$user=(new \yii\db\Query())
->from('{{%ybwm_member}}')
->where('id=:id',[':id'=>$userId])->one();
$payVipRebate=Config::getSystemSet('payVipRebate',$user['uniacid']);
$store=Config::getStoreSet('delivery',$storeId);
if($store['type']!=3){
$storeInfo=(new \yii\db\Query())
->from('{{%ybwm_store}}')
->where('id=:id',[':id'=>$storeId])->one();
$distance=getDistance($startLat,$startLng,$storeInfo['lat'],$storeInfo['lng']);
if($distance>$store['range'] AND $store['range']>0){
return false;
}
}
if($store['type']==1){
$money['startMoney']=$store['fixedStartMoney'];
$timeArr=$store['timeArr'];
$money['money']=$store['money'];
if($timeArr){
for($i=0;$i<count($timeArr);$i++){
$startTime=strtotime(date("Y-m-d ".$timeArr[$i]['startTime']));
$endTime=strtotime(date("Y-m-d ".$timeArr[$i]['endTime']));
if(time()>=$startTime AND time()<=$endTime){
$money['money']=bcadd($store['money'],$timeArr[$i]['money'],2);
break;
}
}
}
}
if($store['type']==2){
$money=self::getDistanceDeliveryMoney($startLat,$startLng,$storeId);
}
if($store['type']==3){
$money=self::getAreaDeliveryMoney($startLat,$startLng,$storeId);
if(!$money){
return false;
}
}
$money['money']=$money['money']?:0;
$money['startMoney']=$money['startMoney']?:0;
$now=time();
$delivery=(new \yii\db\Query())
->from('{{%ybwm_delivery_preferential}}')
->where('display=1 AND deleteAt=0 AND storeId=:storeId AND startTime<=:startTime AND endTime>=:endTime',['startTime'=>$now,'endTime'=>$now,'storeId'=>$storeId])
->andWhere(['like','week',date('w')])
->one();
if(!$delivery){
$money['oldMoney']=0;//原配送费
$money['discount']=0;//优惠配送费
}
if($delivery['type']==1){
$money['oldMoney']=$money['money'];//原配送费
$money['discount']=$delivery['money']>$money['money']?$money['money']:$delivery['money'];//优惠配送费
$money['money']=bcsub($money['money'],$delivery['money'],2)>0?bcsub($money['money'],$delivery['money'],2):0;
}else{
$reductionArr=json_decode($delivery['reductionArr'],true);
array_multisort(array_column($reductionArr,'fullMoney'),SORT_DESC,$reductionArr);
for($i=0;$i<count($reductionArr);$i++){
if($reductionArr[$i]['fullMoney']<=$orderMoney){
if($reductionArr[$i]['isFree']==1){
$money['oldMoney']=$money['money'];//原配送费
$money['discount']=$money['money'];//优惠配送费
$money['money']=0;
}else{
$money['oldMoney']=$money['money'];//原配送费
$money['discount']=$reductionArr[$i]['money']>$money['money']?$money['money']:$reductionArr[$i]['money'];//优惠配送费
$money['money']=bcsub($money['money'],$reductionArr[$i]['money'],2)>0?bcsub($money['money'],$reductionArr[$i]['money'],2):0;//现配送费
}
break;
}
}
}
if($payVipRebate['deliveryOpen']==1 AND $user['vipEndTime']>time()){
return [
'oldMoney'=>$money['money'],
'discount'=>$money['money'],
'money'=>0,
];
}
return $money;
}
//计算购物车价格
public static function getCarMoney($userId, $storeId,$item=1,$tableId=0){
$money=(new \yii\db\Query())
->select(['CAST(sum(originalMoney*(num-discountNum)+originalDiscountPrice*discountNum+materialMoney*num) AS decimal(10,2)) as originalMoney','CAST(sum(money*(num-discountNum)+discountPrice*discountNum+materialMoney*num) AS decimal(10,2)) as goodsMoney','CAST(sum(boxMoney*num) AS decimal(10,2)) as boxMoney','sum(num) as goodsNum'])
->from('{{%ybwm_shop_car}}')
->where('tableId=:tableId AND userId=:userId AND storeId=:storeId AND item=:item',[':tableId'=>$tableId,':userId'=>$userId,':item'=>$item,'storeId'=>$storeId])
->one();
if($tableId){
$storeSet = Config::getStoreSet('instoreSet', $storeId);
if($storeSet['orderMode']==1){
$money=(new \yii\db\Query())
->select(['CAST(sum(originalMoney*(num-discountNum)+originalDiscountPrice*discountNum+materialMoney*num) AS decimal(10,2)) as originalMoney','CAST(sum(money*(num-discountNum)+discountPrice*discountNum+materialMoney*num) AS decimal(10,2)) as goodsMoney','CAST(sum(boxMoney*num) AS decimal(10,2)) as boxMoney','sum(num) as goodsNum'])
->from('{{%ybwm_shop_car}}')
->where('tableId=:tableId AND storeId=:storeId AND item=:item',[':tableId'=>$tableId,':item'=>$item,'storeId'=>$storeId])
->one();
}
}
return $money;
}
//取消订单
public static function cancel($orderId,$auto=false) {
$order = (new \yii\db\Query())
->select('storeId,uniacid,state,couponId,money')
->from('{{%ybwm_takeout_order}}')
->where('id=:id', [':id' => $orderId])->one();
$transaction = Yii::$app->db->beginTransaction(); //开始事务
if($order['state']==1){
$res = YII::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', ['state'=>7,'changeAt'=>time()], ['id'=>$orderId])->execute();
}
if($order['state']==2){
//接单前取消并退款
$data['changeAt']=time();
$data['state']=10;
$data['refundNo']=date("YmdHis") . rand(111111, 999999);
$data['refundMoney']=$order['money'];
$data['refundType']=3;
$res = YII::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $data, ['id'=>$orderId])->execute();
$refund=self::refund($orderId);
if(!$refund){
$transaction->rollBack();//事务回滚
return false;
}
// $stock=self::reduceStock($orderId,2);
// if(!$stock){
// $transaction->rollBack();//事务回滚
// return false;
// }
$bill=Bill::refundBill($orderId,1);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
self::takeoutVoice($orderId, 'chargeback');
}
if($res){
$stock=self::reduceStock($orderId,2);
if(!$stock){
$transaction->rollBack();//事务回滚
return false;
}
if($order['couponId']){
$useCoupon=self::cancelCoupon(json_decode($order['couponId'],true));//归还优惠券
if(!$useCoupon){
$transaction->rollBack();//事务回滚
return false;
}
}
if($auto){
CallbackOrder::voiceType($order['uniacid'],$order['storeId'],'cancelOrder',$orderId);
}
$transaction->commit();
return true;
}else{
return false;
}
}
//取消优惠券
public static function cancelCoupon($couponId) {
if($couponId['store']){
$useCoupon = Yii::$app->db->createCommand()->update('{{%ybwm_user_coupon}}', ['state'=>2,'useTime'=>0], 'id=:id', ['id' =>$couponId['store']])->execute();
if(!$useCoupon){
return false;
}
}
if($couponId['platform']){
$platformUseCoupon = Yii::$app->db->createCommand()->update('{{%ybwm_user_coupon}}', ['state'=>2,'useTime'=>0], 'id=:id', ['id' =>$couponId['platform']])->execute();
if(!$platformUseCoupon){
return false;
}
}
return true;
}
//接单
public static function receipt($orderId) {
$order=$table=(new \yii\db\Query())
->select('storeId,state,deliveryMode,appointment')
->from('{{%ybwm_takeout_order}}')
->where('id=:id',[':id'=>$orderId])->one();
$set=Config::getStoreSet('takeOutSet',$order['storeId']);
if($order['state']!=2){
return '订单状态异常';
}
$storeSet=Config::getStoreSet('deliveryMode',$order['storeId']);
$data['state']=3;
if($order['deliveryMode']==10){
$data['state']=4;//自提接单
}
$data['receiptAt']=time();
$res = YII::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $data, ['id'=>$orderId])->execute();
if(!$res){
return false;
}
if($storeSet['automatic']==1 AND $order['deliveryMode']!=10 AND $order['appointment']==2){
//自动配送
$ps=self::distribution($orderId);
if(!$ps){
return false;
}
}
if($set['printType']==2){
Printing::orderPrint($orderId,1);
}
Message::receipt($orderId);//接单模板消息
return true;
}
//拒单
public static function rejection($orderId) {
$order=(new \yii\db\Query())
->select('money,couponId,state,payMode')
->from('{{%ybwm_takeout_order}}')
->where('id=:id',[':id'=>$orderId])->one();
if($order['state']!=2){
return false;
}
$transaction = Yii::$app->db->beginTransaction(); //开始事务
$data['state']=8;
$data['changeAt']=time();
$data['refundNo']=date("YmdHis") . rand(111111, 999999);
$data['refundMoney']=$order['money'];
$res = Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $data, ['id'=>$orderId])->execute();
if(!$res){
return false;
}
if($order['payMode']!=10){
$refund=self::refund($orderId);
if(!$refund){
$transaction->rollBack();//事务回滚
return false;
}
}
$stock=self::reduceStock($orderId,2);
if(!$stock){
$transaction->rollBack();//事务回滚
return false;
}
$bill=Bill::refundBill($orderId,2);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
if($order['couponId']){
$useCoupon=self::cancelCoupon(json_decode($order['couponId'],true));//归还优惠券
if(!$useCoupon){
$transaction->rollBack();//事务回滚
return false;
}
}
$transaction->commit();//提交事务
Message::rejection($orderId);//拒单模板消息
return true;
}
//出餐
public static function mealOut($orderId) {
//出餐
$data['mealOutState']=1;
$data['mealOutTime']=time();
$res = Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $data, ['id'=>$orderId])->execute();
if($res){
return true;
}else{
return false;
}
}
//配送
public static function distribution($orderId,$type=null) {
$order=(new \yii\db\Query())
->from('{{%ybwm_takeout_order}}')
->where('id=:id',[':id'=>$orderId])->one();
if(!$type){
$type=$order['deliveryMode'];
}else{
YII::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', ['deliveryMode'=>$type], ['id'=>$orderId])->execute();
}
if($type==1){
YII::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', ['state'=>4], ['id'=>$orderId])->execute();
Message::delivery($orderId);
return true;
}
$res=Delivery::addOrder($orderId,$type);
if($res){
Message::delivery($orderId);
}
return $res;
}
/**通过退款
* @param $orderId
* @param int $type[1.用户申请退款通过 2.商家主动退款]
* @return bool
* @throws \yii\db\Exception
*/
public static function adoptRefund($orderId,$type=1) {
//通过退款
$order=(new \yii\db\Query())
->select('money,couponId,state')
->from('{{%ybwm_takeout_order}}')
->where('id=:id',[':id'=>$orderId])->one();
if($order['state']==10){
return false;
}
$data2['refundMoney']=$order['money'];
$data2['refundNo'] = date("YmdHis") . rand(111111, 999999);
Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $data2, ['id'=>$orderId])->execute();
$transaction = Yii::$app->db->beginTransaction(); //开始事务
$data['state']=10;
$data['refundAdoptAt']=time();
$data['refundType']=2;
$res = Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $data, ['id'=>$orderId])->execute();
if(!$res){
return false;
}
$refund=Order::refund($orderId);
if(!$refund){
$transaction->rollBack();//事务回滚
return false;
}
$bill=Bill::refundBill($orderId,$type);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
$stock=self::reduceStock($orderId,2);
if(!$stock){
$transaction->rollBack();//事务回滚
return false;
}
if($order['couponId']){
$useCoupon=self::cancelCoupon(json_decode($order['couponId'],true));//归还优惠券
if(!$useCoupon){
$transaction->rollBack();//事务回滚
return false;
}
}
$transaction->commit();//提交事务
Delivery::cancelOrder($orderId);
Message::refundResult($orderId);//退款结果
return true;
}
//拒绝退款
public static function refuseRefund($orderId) {
$order=$table=(new \yii\db\Query())
->select('beforeRefundState')
->from('{{%ybwm_takeout_order}}')
->where('id=:id',[':id'=>$orderId])->one();
$data['state']=$order['beforeRefundState'];
$data['refundAdoptAt']=time();
$res = Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $data, ['id'=>$orderId])->execute();
if(!$res){
return false;
}
Message::refundResult($orderId);//退款结果
return true;
}
//减库存加销量 type 1减库存2加库存
public static function reduceStock($orderId,$type=1,$orderType=1) {
if($orderType==1){
$order=(new \yii\db\Query())
->select('storeId,uniacid')
->from('{{%ybwm_takeout_order}}')
->where('id=:id',[':id'=>$orderId])->one();
}
if($orderType==2 || $orderType==3){
$order=(new \yii\db\Query())
->select('storeId,uniacid')
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderId])->one();
}
$store=(new \yii\db\Query())
->select('isMain,goodsModel')
->from('{{%ybwm_store}}')
->where('id=:id',[':id'=>$order['storeId']])->one();
$goods=(new \yii\db\Query())
->from('{{%ybwm_order_goods}}')
->where('orderId=:orderId AND item=:item',[':item'=>$orderType,':orderId'=>$orderId])->all();
if($type==1){
//减库存加销量
$symbol='-';
$salesSymbol='+';
}else{
//加库存减销量
$symbol='+';
$salesSymbol='-';
}
for($i=0;$i<count($goods);$i++){
if($store['isMain']==1||$store['goodsModel']==3){
//ybwm_good_specs SalesStock
if($goods[$i]['groupId']){
Yii::$app->db->createCommand()->update('{{%ybwm_good_specs}}', ['SalesStock'=>new \yii\db\Expression('SalesStock '.$symbol.$goods[$i]['num'])], 'id=:id', ['id' =>$goods[$i]['groupId']])->execute();
}
Yii::$app->db->createCommand()->update('{{%ybwm_core_goods}}', ['stock'=>new \yii\db\Expression('stock '.$symbol.$goods[$i]['num']),'salesNum'=>new \yii\db\Expression('salesNum '.$salesSymbol.$goods[$i]['num'])], 'id=:id', ['id' =>$goods[$i]['goodsId']])->execute();
$synchroStore=(new \yii\db\Query())
->select('id')
->from('{{%ybwm_store}}')
->where('uniacid=:uniacid AND goodsModel=1',[':uniacid'=>$order['uniacid']])->all();
$storeIds=array_column($synchroStore,'id');
Yii::$app->db->createCommand()->update('{{%ybwm_store_goods}}', ['stock'=>new \yii\db\Expression('stock '.$symbol.$goods[$i]['num']),'salesNum'=>new \yii\db\Expression('salesNum '.$salesSymbol.$goods[$i]['num'])], ['and',['goodsId' =>$goods[$i]['goodsId']],['in','storeId',$storeIds]])->execute();
}else{
if($goods[$i]['groupId']){
$storeGoods=(new \yii\db\Query())
->select('data')
->from('{{%ybwm_store_goods}}')
->where('goodsId=:goodsId AND storeId=:storeId', ['goodsId' =>$goods[$i]['goodsId'],'storeId'=>$order['storeId']])->one();
if($storeGoods['data']){
$storeData=json_decode($storeGoods['data'],true);
$goodsData=$storeData['specs'];
for($g=0;$g<count($goodsData);$g++){
if($goodsData[$g]['id']==$goods[$i]['groupId']){
if($type==1) {
$goodsData[$g]['SalesStock'] -=$goods[$i]['num'];
}else{
$goodsData[$g]['SalesStock'] +=$goods[$i]['num'];
}
}
}
$storeData['specs']=[];
$storeData['specs']=$goodsData;
Yii::$app->db->createCommand()->update('{{%ybwm_store_goods}}', ['data'=>json_encode($storeData)], 'goodsId=:goodsId AND storeId=:storeId', ['goodsId' =>$goods[$i]['goodsId'],'storeId'=>$order['storeId']])->execute();
}
if($store['goodsModel']==1){
Yii::$app->db->createCommand()->update('{{%ybwm_good_specs}}', ['SalesStock'=>new \yii\db\Expression('SalesStock '.$symbol.$goods[$i]['num'])], 'id=:id', ['id' =>$goods[$i]['groupId']])->execute();
}
}
Yii::$app->db->createCommand()->update('{{%ybwm_store_goods}}', ['stock'=>new \yii\db\Expression('stock '.$symbol.$goods[$i]['num']),'salesNum'=>new \yii\db\Expression('salesNum '.$salesSymbol.$goods[$i]['num'])], 'goodsId=:goodsId AND storeId=:storeId', ['goodsId' =>$goods[$i]['goodsId'],'storeId'=>$order['storeId']])->execute();
if($store['goodsModel']==1){
Yii::$app->db->createCommand()->update('{{%ybwm_store_goods}}', ['stock'=>new \yii\db\Expression('stock '.$symbol.$goods[$i]['num']),'salesNum'=>new \yii\db\Expression('salesNum '.$salesSymbol.$goods[$i]['num'])], 'id=:id', ['id' =>$goods[$i]['goodsId']])->execute();
}
}
}
return true;
}
//确认收货
public static function receiving($orderId) {
$order=(new \yii\db\Query())
->from('{{%ybwm_takeout_order}}')
->where('id=:id',[':id'=>$orderId])->one();
$data['state']=5;
$data['completeAt']=time();
$transaction = Yii::$app->db->beginTransaction(); //开始事务
$res = Yii::$app->db->createCommand()->update('{{%ybwm_takeout_order}}', $data, 'id=:id', ['id' =>$orderId])->execute();
if(!$res){
$transaction->rollBack();//事务回滚
return false;
}
$bill=Bill::updBill($order['outTradeNo']);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
if($order['profitSharingState']==2 AND $order['profitSharing']==1 AND $order['payMode']==1){
$profitSharing=WeChat::profitSharing($orderId);//分账
if(!$profitSharing){
$transaction->rollBack();//事务回滚
return false;
}
}
$transaction->commit();//提交事务
Member::oldWithNewReward($order['uniacid'],$order['userId']);
Member::distributionReward($order['outTradeNo'],$order['uniacid']);
$system=Config::getSystemSet('currency',$order['uniacid']);
$orderIntegralType=$system['orderIntegralType']?:3;
if($orderIntegralType==1){
Member::saveIntegral($order['userId'],2,$system['integral'],1,'订单积分奖励',$order['uniacid']);//增加积分
}
if($orderIntegralType==2){
Member::saveIntegral($order['userId'],2,bcmul($order['money'],$system['integral']/100,0),1,'订单积分奖励',$order['uniacid']);//增加积分
}
$orderGrowthType=$system['orderGrowthType']?:3;
if($orderGrowthType==1){
Member::saveGrowth($order['userId'],2,$system['growth'],1,'订单成长值奖励',$order['uniacid']);//增加成长值
}
if($orderGrowthType==2){
Member::saveGrowth($order['userId'],2,bcmul($order['money'],$system['growth']/100,0),1,'订单成长值奖励',$order['uniacid']);//增加成长值
}
//支付有礼
$record=(new \yii\db\Query())
->from('{{%ybwm_pay_politely_record}}')
->where('orderId=:orderId AND state=2 AND type=1',[':orderId'=>$orderId])
->one();
if($record){
if($record['balance']>0){
Member::saveBalance($order['userId'],2,$record['balance'],1,'支付有礼',$order['uniacid']);//增加余额
}
if($record['integral']>0){
Member::saveIntegral($order['userId'],2,$record['integral'],1,'支付有礼',$order['uniacid']);//增加积分
}
if($record['coupon']){
Member::receiveCoupon(json_decode($record['coupon'],true),$order['userId'],5);//发放优惠券
}
if($record['growth']>0){
Member::saveGrowth($order['userId'],2,$record['growth'],1,'支付有礼',$order['uniacid']);//增加积分
}
}
return true;
}
//支付退款type 1.外卖2店内
public static function refund($orderId,$type=1) {
if($type==1){
$order=(new \yii\db\Query())
// ->select('payMode,uniacid,payType,subMchId,outTradeNo,refundNo,money,refundMoney,userId')
->from('{{%ybwm_takeout_order}}')
->where('id=:id',[':id'=>$orderId])->one();
}
if($type==2){
$order=(new \yii\db\Query())
// ->select('payMode,uniacid,payType,subMchId,outTradeNo,refundNo,money,refundMoney,userId')
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderId])->one();
}
if($type==3){
$order=(new \yii\db\Query())
// ->select('payMode,uniacid,payType,subMchId,outTradeNo,refundNo,money,refundMoney,userId')
->from('{{%ybwm_appointment}}')
->where('id=:id',[':id'=>$orderId])->one();
}
if($order['payMode']==1){
//调退款接口
$fuiouObj = new FuiouController();
$res = $fuiouObj->refund($order);
/***原退款方式 start**/
// $res=WeChat::wxRefund($order['uniacid'],1,$order['payType'],$order['subMchId'],$order['outTradeNo'],$order['refundNo'],$order['money'],$order['refundMoney']);
/***原退款方式 end**/
if($res){
if($type==1) {
Printing::refundOrderPrint($orderId);
}
return true;
}else{
echo json_encode(['code'=>2,'msg'=>$res['err_code_des']]);die;
//return false;
}
}elseif($order['payMode']==2){
// $res=Ali::refund($order['uniacid'],$order['outTradeNo'],$order['refundMoney']);
//调退款接口
$fuiouObj = new FuiouController();
$res = $fuiouObj->refund($order);
if($res){
if($type==1) {
Printing::refundOrderPrint($orderId);
}
return true;
}else{
return false;
}
}elseif($order['payMode']==3){
$res=ZiJie::refund($order['uniacid'],$order['outTradeNo'],$order['refundMoney'],$order['refundNo']);
if($res===true){
if($type==1) {
Printing::refundOrderPrint($orderId);
}
return true;
}else{
return false;
}
}elseif($order['payMode']==5){
//余额支付
$res=Member::saveBalance($order['userId'],2,$order['refundMoney'],1,'订单退款',$order['uniacid']);
if($res){
if($type==1) {
Printing::refundOrderPrint($orderId);
}
return true;
}else{
return false;
}
}
return true;
}
//新客立减
public static function newReduction($userId,$storeId,$orderType=1) {
if($orderType>1){
return 0;
}
$now=time();
$userOrder=(new \yii\db\Query())
->select('id')
->from('{{%ybwm_takeout_order}}')
->where('storeId=:storeId AND userId=:userId',[':userId'=>$userId,':storeId'=>$storeId])
->andWhere(['not in','state',[7,8,10]])
->one();
if($userOrder){
return 0;
}
$userOrder=(new \yii\db\Query())
->select('id')
->from('{{%ybwm_instore_order}}')
->where('storeId=:storeId AND userId=:userId',[':userId'=>$userId,':storeId'=>$storeId])
->andWhere(['in','state',[2,3]])
->one();
if($userOrder){
return 0;
}
$res=(new \yii\db\Query())
->select('money')
->from('{{%ybwm_new_reduction}}')
->where('storeId=:storeId AND startTime<=:startTime AND endTime>:endTime AND deleteAt=0 AND display=1',[':startTime'=>$now,':endTime'=>$now,':storeId'=>$storeId])->one();
return $res['money']?:0;
}
//计算满减
public static function reduce($storeId,$userId,$money,$item=1) {
$now=time();
$stor = (new \yii\db\Query())
->select(['id','name','storeNumber','uniacid'])
->from('{{%ybwm_store}}')
->where(['id'=>$storeId])
->one();
$uniacid = !empty($stor) ? $stor['uniacid'] :0;
$res=(new \yii\db\Query())
->from('{{%ybwm_store_reduce}}')
->where('deleteAt=0 AND display=1 AND startTime<=:startTime AND endTime>:endTime',[':startTime'=>$now,':endTime'=>$now])
->andWhere(['uniacid'=>$uniacid])
->andWhere(['like','week',date('w')])
->andWhere(['like','useType',$item])
->andWhere(['or',['storeId'=>$storeId,'storeType'=>1],['storeType'=>2],['and',['storeType'=>3],['like','storeArr',$storeId]]])
->one();
if(!$res){
return ['id'=>0,'money'=>0];
}
$discount=json_decode($res['moneyArr'],true);
//array_multisort(array_column($discount,'fullMoney'),SORT_DESC,$discount);
$data['id']=$res['id'];
if($res['people']==2){
//新客
$userOrder=self::isNew($storeId,$userId,$item);
if($userOrder==1){
return ['id'=>0,'money'=>0];
}
}
if($res['people']==3){
//会员
return ['id'=>0,'money'=>0];
}
if($res['type']==1){
//每满多少优惠
$data['money'] = floor($money / $discount[0]['fullMoney']) * $discount[0]['money'];
return $data;
}else{
//多级优惠 循环判断满足哪一级
$discountMoney = 0;
for ($i = 0; $i < count($discount); $i++) {
if ($discount[$i]['fullMoney'] <= $money) {
$discountMoney = $discount[$i]['money'];
break;
}
}
$data['money'] = $discountMoney;
return $data;
}
}
//查看是否是新客
public static function isNew($storeId,$userId,$item=1) {
if($item==1){
$userOrder=(new \yii\db\Query())
->select('id')
->from('{{%ybwm_takeout_order}}')
->where('storeId=:storeId AND userId=:userId',[':userId'=>$userId,':storeId'=>$storeId])
->andWhere(['not in','state',[7,8,10]])
->one();
if($userOrder){
return 1;
}
}
if($item==2){
$userOrder=(new \yii\db\Query())
->select('id')
->from('{{%ybwm_instore_order}}')
->where('storeId=:storeId AND userId=:userId AND orderMode=1',[':userId'=>$userId,':storeId'=>$storeId])
->andWhere(['not in','state',[4,5]])
->one();
if($userOrder){
return 1;
}
}
if($item==3){
$userOrder=(new \yii\db\Query())
->select('id')
->from('{{%ybwm_instore_order}}')
->where('storeId=:storeId AND userId=:userId AND orderMode=2',[':userId'=>$userId,':storeId'=>$storeId])
->andWhere(['not in','state',[5,7,9]])
->one();
if($userOrder){
return 1;
}
}
return 2;
}
//查看满赠
public static function give($storeId,$money,$item=1) {
$now=time();
$give=(new \yii\db\Query())
->from('{{%ybwm_give}}')
->where('storeId=:storeId AND deleteAt=0 AND display=1 AND startTime<=:startTime AND endTime>:endTime',[':startTime'=>$now,':endTime'=>$now,':storeId'=>$storeId])
->andWhere(['like','week',date('w')])
->andWhere(['like','useType',$item])
->one();
if(!$give){
return '';
}
$moneyArr=json_decode($give['moneyArr'],true);
for($i=0;$i<count($moneyArr);$i++){
if($money>=$moneyArr[$i]['fullMoney']){
return $moneyArr[$i]['give'];
}
}
return '';
}
//外卖订单语音
public static function takeoutVoice($orderId,$orderType){
$order = (new \yii\db\Query())
->select('id,storeId,uniacid,money,takeNo')
->from('{{%ybwm_takeout_order}}')
->where('id=:id', [':id' => $orderId])->one();
$orderGoods=(new \yii\db\Query())
->select(['name'])
->from('{{%ybwm_order_goods}}')
->where('orderId=:orderId AND item=1',[':orderId'=>$orderId])->all();
$goodsName='';
for($i=0;$i<count($orderGoods);$i++){
$goodsName.=$orderGoods[$i]['name'];
}
$res= Voice::noticeVoice($order['uniacid'], $order['storeId'], 1, $orderType, ['orderNumber' => $order['takeNo'], 'money' => $order['money'], 'variety' => $goodsName]);
//file_put_contents('3366.log',$res);
}
//堂食订单语音
public static function instoreVoice($orderId,$orderType){
$order = (new \yii\db\Query())
->select('id,storeId,uniacid,money,takeNo,regionName,typeName,number,callNo')
->from('{{%ybwm_instore_order}}')
->where('id=:id', [':id' => $orderId])->one();
$order['typeName']=substr( $order['typeName'], 0, strrpos( $order['typeName'], '('));
$tableName=$order['regionName'].$order['typeName'].$order['number'];
Voice::noticeVoice($order['uniacid'], $order['storeId'], 2, $orderType, ['takeNo' => $order['callNo'], 'money' => $order['money'],'table'=>$tableName]);
}
//收银订单语音
public static function cashierVoice($orderId,$orderType){
$order = (new \yii\db\Query())
->select('id,money,storeId,uniacid')
->from('{{%ybwm_cashier_order}}')
->where('id=:id', [':id' => $orderId])->one();
Voice::noticeVoice($order['uniacid'], $order['storeId'], 3, $orderType, ['money' => $order['money']]);
//file_put_contents('1.log',$bool);
}
//制作时间
public static function productionTime($storeId){
$makeTime = Config::getStoreSet('makeTime',$storeId);
if($makeTime['open']==2){
return 0;
}
$makeTime['time']=$makeTime['time']?:3;
$makeTime['type']=$makeTime['type']?:1;
if($makeTime['type']==1){
//按单
$orderCount=(new \yii\db\Query())
->from('{{%ybwm_takeout_order}}')
->where('storeId=:storeId AND ((state=3 AND deliveryMode!=10) or (deliveryMode=10 AND state=4) )',[':storeId'=>$storeId])
->count();
}else{
//按件
$orderCount=(new \yii\db\Query())
->from('{{%ybwm_takeout_order}}')
->where('storeId=:storeId AND ((state=3 AND deliveryMode!=10) or (deliveryMode=10 AND state=4) )',[':storeId'=>$storeId])
->sum('num');
}
return bcmul($orderCount+1,$makeTime['time'],0);
}
//快餐接单
public static function fastReceipt($orderId) {
$order=$table=(new \yii\db\Query())
->select('storeId,state')
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderId])->one();
if($order['state']!=2){
return '订单状态异常';
}
$data['state']=3;
$data['receiptAt']=time();
$data['changeAt']=time();
$res = YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', $data, ['id'=>$orderId])->execute();
if(!$res){
return false;
}
$fastData=self::fastScreen($order['storeId']);
Yii::$app->redis->set('fastBy'.$order['storeId'],json_encode($fastData));
return true;
}
//快餐拒单
public static function fastRejection($orderId) {
$order=(new \yii\db\Query())
->select('money,couponId')
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderId])->one();
$transaction = Yii::$app->db->beginTransaction(); //开始事务
$data['state']=9;
$data['changeAt']=time();
$data['refundNo']=date("YmdHis") . rand(111111, 999999);
$data['refundMoney']=$order['money'];
$res = Yii::$app->db->createCommand()->update('{{%ybwm_instore_order}}', $data, ['id'=>$orderId])->execute();
if(!$res){
return false;
}
$refund=self::refund($orderId,2);
if(!$refund){
$transaction->rollBack();//事务回滚
return false;
}
$stock=self::reduceStock($orderId,2,3);
if(!$stock){
$transaction->rollBack();//事务回滚
return false;
}
$bill=Bill::refundBill($orderId,2,2);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
if($order['couponId']){
$useCoupon=self::cancelCoupon(json_decode($order['couponId'],true));//归还优惠券
if(!$useCoupon){
$transaction->rollBack();//事务回滚
return false;
}
}
$fastData=self::fastScreen($order['storeId']);
Yii::$app->redis->set('fastBy'.$order['storeId'],json_encode($fastData));
$transaction->commit();//提交事务
return true;
}
//快餐完成
public static function fastComplete($orderId) {
$order=(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderId])->one();
$data['state']=4;
$data['completeAt']=time();
$data['changeAt']=time();
$transaction = Yii::$app->db->beginTransaction(); //开始事务
$res = Yii::$app->db->createCommand()->update('{{%ybwm_instore_order}}', $data, 'id=:id', ['id' =>$orderId])->execute();
if(!$res){
$transaction->rollBack();//事务回滚
return false;
}
$bill=Bill::updBill($order['outTradeNo']);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
// if($order['profitSharingState']==2 AND $order['profitSharing']==1){
//
// $profitSharing=WeChat::profitSharing($orderId);//分账
// if(!$profitSharing){
// $transaction->rollBack();//事务回滚
// return false;
// }
// }
Member::distributionReward($order['outTradeNo'],$order['uniacid']);
$system=Config::getSystemSet('currency',$order['uniacid']);
$orderIntegralType=$system['orderIntegralType']?:3;
if($orderIntegralType==1){
Member::saveIntegral($order['userId'],2,$system['integral'],1,'订单积分奖励',$order['uniacid']);//增加积分
}
if($orderIntegralType==2){
Member::saveIntegral($order['userId'],2,bcmul($order['money'],$system['integral']/100,0),1,'订单积分奖励',$order['uniacid']);//增加积分
}
$orderGrowthType=$system['orderGrowthType']?:3;
if($orderGrowthType==1){
Member::saveGrowth($order['userId'],2,$system['growth'],1,'订单成长值奖励',$order['uniacid']);//增加成长值
}
if($orderGrowthType==2){
Member::saveGrowth($order['userId'],2,bcmul($order['money'],$system['growth']/100,0),1,'订单成长值奖励',$order['uniacid']);//增加成长值
}
$fastData=self::fastScreen($order['storeId']);
Yii::$app->redis->set('fastBy'.$order['storeId'],json_encode($fastData));
$transaction->commit();//提交事务
self::instoreVoice($orderId,'fastPickOrder');
return true;
}
//快餐取消订单
public static function fastCancel($orderId) {
$order = (new \yii\db\Query())
->select('storeId,uniacid,state,couponId,money')
->from('{{%ybwm_instore_order}}')
->where('id=:id', [':id' => $orderId])->one();
$transaction = Yii::$app->db->beginTransaction(); //开始事务
if($order['state']==1){
$res = YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', ['state'=>5,'changeAt'=>time()], ['id'=>$orderId])->execute();
}
if($order['state']==2 || $order['state']==3){
//接单前取消并退款
$data['changeAt']=time();
$data['state']=7;
$data['refundNo']=date("YmdHis") . rand(111111, 999999);
$data['refundMoney']=$order['money'];
if($order['state']==2){
$data['refundType']=1;
}else{
$data['refundType']=2;
}
$res = YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', $data, ['id'=>$orderId])->execute();
$refund=self::refund($orderId,2);
if(!$refund){
$transaction->rollBack();//事务回滚
return false;
}
$stock=self::reduceStock($orderId,2,3);
if(!$stock){
$transaction->rollBack();//事务回滚
return false;
}
$bill=Bill::refundBill($orderId,1,2);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
//self::takeoutVoice($orderId, 'chargeback');
}
$fastData=self::fastScreen($order['storeId']);
Yii::$app->redis->set('fastBy'.$order['storeId'],json_encode($fastData));
if($res){
if($order['couponId']){
$useCoupon=self::cancelCoupon(json_decode($order['couponId'],true));//归还优惠券
if(!$useCoupon){
$transaction->rollBack();//事务回滚
return false;
}
}
//CallbackOrder::voiceType($order['uniacid'],$order['storeId'],'cancelOrder');
$transaction->commit();
return true;
}else{
return false;
}
}
//快餐叫号
public static function fastCall($orderId) {
$order = (new \yii\db\Query())
->select('storeId,uniacid,state,callNo')
->from('{{%ybwm_instore_order}}')
->where('id=:id', [':id' => $orderId])->one();
Yii::$app->db->createCommand()->update('{{%ybwm_instore_order}}', ['changeAt'=>time(),'callNum'=>new \yii\db\Expression('callNum +1')], 'id=:id', ['id' =>$orderId])->execute();
//删除前日音频数据
$yesterday = date("Ymd", strtotime("-1 day"));
$path = Yii::$app->basePath . '/web/static/music/' . $yesterday;
if (file_exists($path)) {
deldir($path);
}
//echo Yii::$app->basePath . "/models/baidu/AipSpeech.php";die;
// include Yii::$app->basePath . "/models/baidu/AipSpeech.php";
$word = Config::getStoreSet('fastSet', $order['storeId']);
$voiceSet = Config::getSystemSet('voiceSet', $order['uniacid']);
$appId = $voiceSet['appId'];
$appKey = $voiceSet['apiKey'];
$secretKey = $voiceSet['secretKey'];
try{
Message::fastTake($orderId);
}catch (\Exception $e){
}
$fastData=self::fastScreen($order['storeId']);
Yii::$app->redis->set('fastBy'.$order['storeId'],json_encode($fastData));
if (!$appId or !$appKey or !$secretKey) {
return false;
}
$please = $word['phoneticWritingStart'] ?: '请';
$eat = $word['phoneticWritingEnd'] ?: '号用餐';
$content = $please . $order['callNo'] . $eat;
$client = new AipSpeech($appId, $appKey, $secretKey);
$result = $client->synthesis($content, 'zh', 1, array(
'vol' => 10,
));
if (!is_array($result)) {
$path=Yii::$app->basePath."/web/static/music/".date('Ymd');
if (!is_dir($path)) {
mkdir($path, 0777, true); //创建目录
}
$src = Yii::$app->basePath . '/web/static/music/' . date('Ymd') . '/fast' . $orderId . '.mp3';
$rst = true;
if (!file_exists($src)) {
$rst = file_put_contents($src, $result);
}
if ($rst) {
$returnPath='/web/static/music/' . date('Ymd') . '/fast' . $orderId . '.mp3';
if(Yii::$app->params['isDev']==true){
return Yii::$app->request->hostInfo.'/addons/yb_wm/'.$returnPath;
}else{
return Yii::$app->request->hostInfo.'/'.$returnPath;
}
}
}
return true;
}
//排队叫号
public static function queuingCall($orderId) {
$order = (new \yii\db\Query())
->select('storeId,uniacid,state,code')
->from('{{%ybwm_queuing}}')
->where('id=:id', [':id' => $orderId])->one();
//删除前日音频数据
$yesterday = date("Ymd", strtotime("-1 day"));
$path = Yii::$app->basePath . '/web/static/music/' . $yesterday;
if (file_exists($path)) {
deldir($path);
}
//echo Yii::$app->basePath . "/models/baidu/AipSpeech.php";die;
// include Yii::$app->basePath . "/models/baidu/AipSpeech.php";
$word = Config::getStoreSet('queuing', $order['storeId']);
$voiceSet = Config::getSystemSet('voiceSet', $order['uniacid']);
$appId = $voiceSet['appId'];
$appKey = $voiceSet['apiKey'];
$secretKey = $voiceSet['secretKey'];
if (!$appId or !$appKey or !$secretKey) {
return false;
}
$please = $word['please'] ?: '请';
$eat = $word['content'] ?: '号用餐';
$content = $please . $order['code'] . $eat;
$client = new AipSpeech($appId, $appKey, $secretKey);
$result = $client->synthesis($content, 'zh', 1, array(
'vol' => 10,
));
if (!is_array($result)) {
$path=Yii::$app->basePath."/web/static/music/".date('Ymd');
if (!is_dir($path)) {
mkdir($path, 0777, true); //创建目录
}
$src = Yii::$app->basePath . '/web/static/music/' . date('Ymd') . '/queuing' . $orderId . '.mp3';
$rst = true;
if (!file_exists($src)) {
$rst = file_put_contents($src, $result);
}
if ($rst) {
$returnPath='/web/static/music/' . date('Ymd') . '/queuing' . $orderId . '.mp3';
if(Yii::$app->params['isDev']==true){
return Yii::$app->request->hostInfo.'/addons/yb_wm/'.$returnPath;
}else{
return Yii::$app->request->hostInfo.'/'.$returnPath;
}
}
}
return false;
}
//堂食接单
public static function inStoreReceipt($orderId){
$order=$table=(new \yii\db\Query())
->select('storeId,state,tableId')
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderId])->one();
if($order['state']!=1){
return false;
}
$data['state']=2;
$data['changeAt']=time();
$data['receiptAt']=time();
$res = YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', $data, ['id'=>$orderId])->execute();
if(!$res){
return false;
}
Message::inStoreOrder($orderId);
YII::$app->db->createCommand()->update('{{%ybwm_table}}', ['state'=>3], ['id'=>$order['tableId']])->execute();
return true;
}
//堂食关闭订单
public static function inStoreClose($orderId){
$order=(new \yii\db\Query())
->select('storeId,state,userId,tableId,couponId')
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderId])->one();
$data['state']=4;
$data['changeAt']=time();
$res = YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', $data, ['id'=>$orderId])->execute();
if(!$res){
return false;
}
$storeSet = Config::getStoreSet('instoreSet', $order['storeId']);
if($storeSet['orderMode']==1){
Yii::$app->db->createCommand()->delete('{{%ybwm_shop_car}}',['item'=>2,'tableId'=>$order['tableId'],'storeId'=>$order['storeId']])->execute();
}
Yii::$app->db->createCommand()->delete('{{%ybwm_cashier_goods}}',['tableId'=>$order['tableId'],'storeId'=>$order['storeId']])->execute();
YII::$app->db->createCommand()->update('{{%ybwm_table}}', ['state'=>1,'userId'=>0], ['id'=>$order['tableId']])->execute();
if($order['couponId']){
$useCoupon=self::cancelCoupon(json_decode($order['couponId'],true));//归还优惠券
if(!$useCoupon){
return false;
}
}
return true;
}
//结账
public static function inStoreCheckOut($orderId){
$order=(new \yii\db\Query())
->select('tableId,uniacid,outTradeNo,eatType,money,userId')
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderId])->one();
if($order['eatType']==1){
$data['completeAt']=time();
}else{
$data['payMode']=6;
$data['payAt']=time();
$data['completeAt']=time();
}
$data['state']=3;
$data['changeAt']=time();
$transaction = Yii::$app->db->beginTransaction(); //开始事务
$res = YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', $data, ['id'=>$orderId])->execute();
if(!$res){
$transaction->rollBack();
return false;
}
YII::$app->db->createCommand()->update('{{%ybwm_table}}', ['state'=>1,'userId'=>0], ['id'=>$order['tableId']])->execute();
if($order['eatType']==2) {
Printing::orderPrint($orderId, 2,'',false);
self::instoreVoice($orderId,'inOutOrder');
}
if($order['eatType']==1) {
//餐前支付
$bill=Bill::updBill($order['outTradeNo']);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
$transaction->commit();
if($order['userId']){
Member::distributionReward($order['outTradeNo'],$order['uniacid']);//分销奖励
$system=Config::getSystemSet('currency',$order['uniacid']);
$orderIntegralType=$system['orderIntegralType']?:3;
if($orderIntegralType==1){
Member::saveIntegral($order['userId'],2,$system['integral'],1,'订单积分奖励',$order['uniacid']);//增加积分
}
if($orderIntegralType==2){
Member::saveIntegral($order['userId'],2,bcmul($order['money'],$system['integral']/100,0),1,'订单积分奖励',$order['uniacid']);//增加积分
}
$orderGrowthType=$system['orderGrowthType']?:3;
if($orderGrowthType==1){
Member::saveGrowth($order['userId'],2,$system['growth'],1,'订单成长值奖励',$order['uniacid']);//增加成长值
}
if($orderGrowthType==2){
Member::saveGrowth($order['userId'],2,bcmul($order['money'],$system['growth']/100,0),1,'订单成长值奖励',$order['uniacid']);//增加成长值
}
}
}else{
$bill=Bill::bill($order['uniacid'],2,7,$order['outTradeNo'],1);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
$transaction->commit();
}
return true;
}
//富友退款
public static function inStoreFuiouRefund($orderId,$money = 0){
$order=(new \yii\db\Query())
->select('eatType,origin,storeId,state,userId,money,tableId')
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderId])->one();
// }
if($order['origin']==3){
echo json_encode(['code'=>2,'msg'=>'订单已完成无法退款']);die;
}
switch ($order['state']){
case 1;
echo json_encode(['code'=>2,'msg'=>'订单未支付']);die;
break;
case 4;
echo json_encode(['code'=>2,'msg'=>'订单已关闭']);die;
break;
case 5;
echo json_encode(['code'=>2,'msg'=>'订单已退款,请勿重复操作']);die;
break;
}
$data['state']=5;
$data['refundNo']=date("YmdHis") . rand(111111, 999999);
$data['refundMoney'] = $money?:$order['money'];
$data['changeAt'] = time();
$transaction = Yii::$app->db->beginTransaction(); //开始事务
$res = YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', $data, ['id'=>$orderId])->execute();
if(!$res){
$transaction->rollBack();
return false;
}
if($order['eatType']==1){
Order::reduceStock($orderId,2,2);
}
$refund=self::refund($orderId,2);
if(!$refund){
$transaction->rollBack();//事务回滚
return false;
}
$bill=Bill::refundBill($orderId,2,2);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
YII::$app->db->createCommand()->update('{{%ybwm_table}}', ['state'=>1,'userId'=>0], ['id'=>$order['tableId']])->execute();
$transaction->commit();
return true;
}
//退款
public static function inStoreRefund($orderId,$money=0){
$order=(new \yii\db\Query())
->select('eatType,origin,storeId,state,userId,money,tableId')
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderId])->one();
// if($order['origin']==5){
// echo json_encode(['code'=>2,'msg'=>'收银台订单无法退款']);die;
// }
if($order['origin']==3){
echo json_encode(['code'=>2,'msg'=>'订单已完成无法退款']);die;
}
switch ($order['state']){
case 1;
echo json_encode(['code'=>2,'msg'=>'订单未支付']);die;
break;
case 4;
echo json_encode(['code'=>2,'msg'=>'订单已关闭']);die;
break;
case 5;
echo json_encode(['code'=>2,'msg'=>'订单已退款,请勿重复操作']);die;
break;
}
$data['state']=5;
$data['refundNo']=date("YmdHis") . rand(111111, 999999);
if($money > $order['money']) {
echo json_encode(['code'=>2,'msg'=>'退款金额不能大于订单金额!']);die;
}
$data['refundMoney']=$money?:$order['money'];
$data['changeAt']=time();
$transaction = Yii::$app->db->beginTransaction(); //开始事务
$res = YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', $data, ['id'=>$orderId])->execute();
if(!$res){
$transaction->rollBack();
return false;
}
if($order['eatType']==1){
Order::reduceStock($orderId,2,2);
}
$refund=self::refund($orderId,2);
if(!$refund){
$transaction->rollBack();//事务回滚
return false;
}
$bill=Bill::refundBill($orderId,2,2);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
YII::$app->db->createCommand()->update('{{%ybwm_table}}', ['state'=>1,'userId'=>0], ['id'=>$order['tableId']])->execute();
$transaction->commit();
return true;
}
//计算商品退单多少钱
public static function refundGoodsMoney($orderGoodsId){
$orderGoods=(new \yii\db\Query())
->from('{{%ybwm_order_goods}}')
->where('id=:id',[':id'=>$orderGoodsId])->one();
if(!$orderGoods){
return false;
}
$order=(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderGoods['orderId']])->one();
$proportion=bcdiv($orderGoods['money'],$order['originMoney'],5);//比例
$goodsMoney=bcsub($order['money'],$order['tablewareMoney'],2);//订单优惠后商品价格
$returnMoney=0;
if($goodsMoney==$order['originMoney']){
$returnMoney=$orderGoods['money'];
}else{
$returnMoney=bcmul($goodsMoney,$proportion,2);
}
//var_dump(bccomp($returnMoney,$orderGoods['money'],2));die;
//var_dump(intval(bcsub($returnMoney,$orderGoods['money'],2)));die;
if(bcsub($returnMoney,$orderGoods['money'],2)>0){
//var_dump(1111);
echo json_encode(['code'=>2,'msg'=>'退菜金额有误']);die;
}
return $returnMoney;
}
//验证购物车商品的库存情况
public static function checkStock($uniacid,$storeId,$userId){
$carData=(new \yii\db\Query())
->select(['goodsId'])
->from('{{%ybwm_shop_car}}')
->where('tableId=:tableId AND userId=:userId AND storeId=:storeId AND item=:item',[':tableId'=>0,':userId'=>$userId,':item'=>1,'storeId'=>$storeId])
->all();
$storeInfo=(new \yii\db\Query())
->from('{{%ybwm_store}}')
->where(['id'=>$storeId])
->one();
foreach ($carData as $v){
if($carData['groupId']){
$goodsInfo=(new \yii\db\Query())->from('{{%ybwm_good_specs}}')->where(['id'=>$v['groupId'],'uniacid'=>$uniacid,'storeId'=>$storeId])->one();
$goodNum=$goodsInfo['SalesStock'];
$goodNamne=$goodsInfo['specsName'];
}else{
if($storeInfo['isMain']==1||$storeInfo['goodsModel']==3){
$goodsInfo=(new \yii\db\Query())->from('{{%ybwm_core_goods}}')->where(['id'=>$v['goodsId'],'uniacid'=>$uniacid,'storeId'=>$storeId])->one();
}else{
$goodsInfo=(new \yii\db\Query())->from('{{%ybwm_store_goods}}')->where(['goodsId'=>$v['goodsId'],'uniacid'=>$uniacid,'storeId'=>$storeId])->one();
}
$goodNum=$goodsInfo['stock'];
$goodNamne=$goodsInfo['name'];
}
if($v['num']>$goodNum){
echo json_encode(['code'=>1,'msg'=>$goodNamne.'库存不足']);die;
continue;
}
}
}
public static function fastScreen($storeId){
$beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
$endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
$store=(new \yii\db\Query())
->select(['name'])
->from('{{%ybwm_store}}')
->where('id=:id',[':id'=>$storeId])->one();
if(!$store){
return [];
}
$where="storeId=:storeId and createdAt>:start and createdAt<=:end and orderMode=2";
$data['storeId']=$storeId;
$data['start']=$beginToday;
$data['end']=$endToday;
$preparing=(new \yii\db\Query())
->select('id,callNo')
->from('{{%ybwm_instore_order}}')
->where($where." AND state=3 AND callNum=0",$data)->orderBy('changeAt desc')->limit('12')->all();
$pleaseTake=(new \yii\db\Query())
->select('id,callNo')
->from('{{%ybwm_instore_order}}')
->where($where." AND state=3 AND callNum>0",$data)->orderBy('changeAt desc')->limit('12')->all();
$list['preparing']=$preparing;
$list['pleaseTake']=$pleaseTake;
$list['storeName']=$store['name'];
$list['number']=count($preparing)?:0;
$list['day']=date('Y-m-d');
$list['type']=2;
return $list;
}
//排队屏幕数据
public static function getQueuingScreenInfo($storeId){
$day=date('Y-m-d');
$count=(new \yii\db\Query())
->from('{{%ybwm_queuing}}')
->where('storeId=:storeId AND day=:day AND deleteAt=0 AND state=1',[':storeId'=>$storeId,':day'=>$day])->count()?:0;
$store=(new \yii\db\Query())
->select(['name'])
->from('{{%ybwm_store}}')
->where('id=:id',[':id'=>$storeId])->one();
$list=(new \yii\db\Query())
->select(['tableId','name','code','count(id) as totalNum','sum(if(state=1,1,0)) as quenNum'])
->from('{{%ybwm_queuing}}')
->where('storeId=:storeId and deleteAt=0 and state=1 and day=:day',[':storeId'=>$storeId,':day'=>$day])->groupBy('tableId')->orderBy('id desc')->all();
foreach ($list as $key => $value) {
$table = (new \yii\db\Query())
->from('{{%ybwm_queuing_type}}')
->where('id=:id',[':id'=> $value['tableId']])->one();
$minute = $table['minute'] * $value['quenNum'];
$list[$key]['minute']=$minute;
$list[$key]['min']=$table['min'];
$list[$key]['max']=$table['max'];
}
$data['list']=$list;
$data['storeName']=$store['name'];
$data['number']=$count;
$list['type']=3;
Yii::$app->redis->set('queuing'.$storeId,json_encode($data));
return $data;
}
//预约取消订单
public static function reserveCancel($orderId,$refundType) {
$order = (new \yii\db\Query())
->select('storeId,uniacid,state,money')
->from('{{%ybwm_appointment}}')
->where('id=:id', [':id' => $orderId])->one();
$transaction = Yii::$app->db->beginTransaction(); //开始事务
$data['changeAt']=time();
$data['state']=$refundType==1?6:4;
$data['refundNo']=date("YmdHis") . rand(111111, 999999);
$data['refundMoney']=$order['money'];
$data['refundType']=$refundType;
$res = YII::$app->db->createCommand()->update('{{%ybwm_appointment}}', $data, ['id'=>$orderId])->execute();
if($res && $order['money']<=0){
$transaction->commit();
return true;
}
$refund=self::refund($orderId,3);
if(!$refund){
$transaction->rollBack();//事务回滚
return false;
}
$bill=Bill::refundBill($orderId,1,3);
if(!$bill){
$transaction->rollBack();//事务回滚
return false;
}
if($res){
$transaction->commit();
return true;
}else{
return false;
}
}
//确认到店
public static function confirmArrival($orderId) {
$order =(new \yii\db\Query())
->select('state,outTradeNo')
->from('{{%ybwm_appointment}}')
->where('id=:id',[':id'=>$orderId])->one();
$res = YII::$app->db->createCommand()->update('{{%ybwm_appointment}}', ['state'=>5,'changeAt'=>time()], ['id'=>$orderId])->execute();
if ($res) {
Bill::updBill($order['outTradeNo']);
return true;
} else {
return false;
}
}
//确认预约成功
public static function adoptAppointment($orderId) {
$res =YII::$app->db->createCommand()->update('{{%ybwm_appointment}}', ['state'=>3,'code' => date('d') . rand(111, 999), 'auditAt' => time(),'changeAt'=>time()], ['id'=>$orderId])->execute();
if ($res) {
return true;
} else {
return false;
}
}
}