canyin-project/ybcy/controllers/channel/CashierOrderController.php
2024-11-01 16:07:54 +08:00

958 lines
43 KiB
PHP

<?php
namespace app\controllers\channel;
use Illuminate\Support\Facades\DB;
use Yii;
use app\models\common\WeChat;
use app\models\common\Bill;
use app\models\common\Store;
use app\models\common\CallbackOrder;
use app\models\common\Member;
use app\models\common\Config;
use Yansongda\Pay\Pay;
use app\models\common\Printing;
use app\models\common\Order;
use yii\web\Session;
use app\controllers\common\FuiouController;
class CashierOrderController extends CommonController{
public $enableCsrfValidation = false;
private $shop_id;
public function init(){
parent::init();
$this->shop_id=Store::getMainStore($this->wqData['uniacid'])['id'];
$request = Yii::$app->request;
if($request->isPost){
if(!$this->shop_id){
echo json_encode(['code'=>2,'msg'=>'无效的门店,请先添加商户']);die;
}
}
}
//购物车商品加入订单
public function saveOrderGoods($uniacid,$storeId,$tableId=0,$orderId){
$operatorId = Yii::$app->session->get('userInfo')['id'];
if (!$operatorId) {
return $this->result(2, '请用收银员账号登录');
}
$carData = (new \yii\db\Query())
->from('{{%ybwm_cashier_goods}}')
->where(['tableId' => $tableId,'state' => 1,'storeId' => $storeId,'uniacid' => $uniacid,'operatorId'=>$operatorId])
->all();
if (!$carData) {
echo json_encode(['code' => 2, 'msg' => '无效的请求']);
die;
}
$transaction = Yii::$app->db->beginTransaction();
try{
foreach ($carData as $v) {
$goodsData = array(
'orderId' => $orderId,
'goodsId' => $v['goodsId'],
'name' => $v['name'],
'money' => $v['money'],
'num' => $v['num'],
'data' => $v['groupName'],
'icon' => $v['icon'],
'storeId' => $v['storeId'],
'uniacid' => $v['uniacid'],
'createdAt' => time(),
'groupId' => $v['groupId']?:0,
'material' => $v['materialName'],
'attribute' => $v['attribute'],
'item' =>3,
);
YII::$app->db->createCommand()->insert('{{%ybwm_order_goods}}', $goodsData)->execute();
}
$transaction->commit();//提交事务会真正的执行数据库操作
return $orderId;
} catch (Exception $e) {
$transaction->rollback();
echo json_encode(['code' => 2, 'msg' =>$e->getMessage()]);die;
}
}
public function actionPay(){
$result=axios_request();
$uniacid = $this->wqData['uniacid'];
$auth_code=trim($result['auth_code']);
$storeId=$result['storeId']?:$this->shop_id;
$payType=$result['payType']?:1;
$tableId=$result['tableId']?:0;
$userId=$result['userId']?:0;
$operatorId= Yii::$app->session->get('userInfo')['id'];
if($payType == 1) {
$bind_data = $this->isBindPayChannel($storeId,$uniacid,1);
}
$payStatus=0;
if($tableId){
$orderInfo=(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('tableId=:tableId',[':tableId'=>$tableId])
->andWhere(['<=','state',2])
->orderBy('id desc')->one();
$orderId =$orderInfo['id'];
}else{
$carData = (new \yii\db\Query())
->from('{{%ybwm_cashier_goods}}')
->where(['tableId' => $tableId,'state' => 1,'storeId' => $storeId,'uniacid' => $uniacid,'operatorId'=>$operatorId])
->all();
if (!$carData) {
echo json_encode(['code' => 2, 'msg' => '无效的请求']);
die;
}
$orderId=array_column($carData,'orderId')[0];
if($orderId&&!$tableId){
YII::$app->db->createCommand()->delete('{{%ybwm_order_goods}}', ['orderId'=> $orderId,'item'=>3])->execute();
// $orderGoodsData = (new \yii\db\Query())
// ->from('{{%ybwm_order_goods}}')
// ->where(['orderId'=> $orderId,'item'=>3])
// ->all();
//if(!$orderGoodsData){
$orderId=$this->saveOrderGoods($uniacid,$storeId,0,$orderId);
//}
}
//店内就餐 打包带走
if($result['isOut']==2){
$fastSet= Config::getStoreSet('fastSet',$storeId);
if($fastSet['boxType']==2){
$boxMoney=0;
foreach ($carData as &$v){
$boxMoney+=bcmul($v['boxMoney'],$v['num'],2);
}
// $boxMoney=array_sum(array_column($carData,'boxMoney'));
}else{
$boxMoney=$fastSet['boxMoney'];
}
$orderInfo=(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('id=:id', [':id' => $orderId])->one();
$money=bcadd($orderInfo['money'],$boxMoney,2);
YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', ['isOut'=>2,'tablewareMoney'=>$boxMoney,'money'=>$money],['id' =>$orderId])->execute();
}
}
if (!$orderId) {
echo json_encode(['code' => 2, 'msg' => '无效的请求']);
die;
}
$orderInfo=(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('id=:id', [':id' => $orderId])->one();
if(!$orderInfo||$orderInfo['state']==3){
return $this->result(2, '无效的单号或订单已支付');
}
if(!$operatorId){
return $this->result(2, '请用收银员账号登录');
}
if($payType=='1'){
if(!$auth_code){
return $this->result(2, '无效的付款码');
}
}
$outTradeNo=$orderInfo['outTradeNo'];
$money=$orderInfo['money'];
if($auth_code){
if(substr($auth_code , 0 , 2)=='28'){
$payModel=2;
}else{
$payModel=1;
}
}
if($result['payType']=='2'){
$payModel=6;
}
if($result['payType']=='3'){
$payModel=5;
}
if($result['payType']=='4'){
if($result['payModel']==1){
$payModel=8;
}
if($result['payModel']==2){
$payModel=9;
}
if($result['payModel']==3){
$payModel=7;
}
}
if($payType==2){
$money=trim($result['money']);
}
if($money<=0){
echo json_encode(['code'=>2,'msg'=>'支付金额异常!']);die;
}
// $cashierSetConfig=Config::getSystemSet('cashierSet',$this->wqData['uniacid']);
// if($cashierSetConfig['discountStatus']==1&&$cashierSetConfig['discountAuto']==1){
// switch ($cashierSetConfig['discountType']){
// case 1;
// $money=substr($orderInfo['money'],0,strlen($orderInfo['money'])-1);
// break;
// case 2;
// $money=intval($orderInfo['money']);
// break;
// case 3;
// $money=round($orderInfo['money'],1);
// break;
// case 4;
// $money=round($orderInfo['money']);
// break;
// }
// $discount=bcsub($orderInfo['money'],$money,2);
// YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', ['discount'=>$discount,'money'=>$money],['id' =>$orderId])->execute();
// }
switch ($payType){
case '1'; //扫码枪支付
if(!$money){
echo json_encode(['code'=>2,'msg'=>'无效的请求']);die;
}
$payStatus = $this->payment2($uniacid,$outTradeNo,$auth_code,$money,$storeId,$payType,$bind_data);
break;
case '2';//现金支付
//$money=trim($result['money']);
if(!$money){
echo json_encode(['code'=>1,'msg'=>'无效的请求']);die;
}
$bool=4;//收银订单
$origin=5;//收银
$payStatus=1;
break;
case '3';//余额支付
if(!$userId){
echo json_encode(['code'=>2,'msg'=>'无效的请求']);die;
}
$user=(new \yii\db\Query())
->select(['id','uniacid','openId','balance'])
->from('{{%ybwm_member}}')
->where('id=:id',[':id'=>$userId])->one();
$userBindData=(new \yii\db\Query())
->from('{{%ybwm_member_bind}}')
->where('userId=:userId and storeId=:storeId', [':userId' => $userId,':storeId' => $storeId])->one();
$note = '快餐订单';
//余额支付
if ($userBindData['balance'] < $orderInfo['money']) {
return $this->result(2, '余额不足!');
}
Member::saveBalance($userId,2,$orderInfo['money'],2,$note,$orderInfo['uniacid'],0,$storeId);//扣除余额
$payStatus=1;
break;
case '4';//用户主动扫码支付
$payStatus=1;
break;
}
//处理支付结果回调
if($payStatus==1){
$transaction = Yii::$app->db->beginTransaction();
try {
YII::$app->db->createCommand()->delete('{{%ybwm_cashier_goods}}',['tableId' => $tableId,'state' => 1,'storeId' => $storeId,'uniacid' => $uniacid,'operatorId'=>$operatorId])->execute();
CallbackOrder::payOrder($orderId,$payModel,$userId);
$transaction->commit();
}catch (Exception $e) {
$transaction->rollBack();
echo json_encode(['code'=>2,'msg'=>$e->getMessage()],320);die;
//获取抛出的错误
// $error = $e->getMessage();
//操作回滚
}
echo json_encode(['code'=>1,'msg'=>'支付成功','data'=>['code'=>'SUCCESS','outTradeNo'=>$orderInfo['outTradeNo'],'payModel'=>$payModel]]);die;
}
}
public function actionCancelOrder(){
$result=axios_request();
$orderId=$result['outTradeNo'];
$outTradeNo = $result['outTradeNo'];
$operatorId = $result['operatorId'];
Yii::$app->db->createCommand()->update('{{%ybwm_cashier_goods}}', ['state'=>4],'outTradeNo=:outTradeNo', [':outTradeNo' => $outTradeNo,'operatorId'=>$operatorId])->execute();
echo json_encode(['code'=>1,'msg'=>'订单已取消']);die;
}
public function payment($uniacid,$outTradeNo,$auth_code,$money,$storeId=null){
//$money=0.01;
if(substr($auth_code , 0 , 2)=='28'){
$aliConfig=Config::getSystemSet('cashierSet',$this->wqData['uniacid']);
if(!$aliConfig){
echo json_encode(['code'=>2,'msg'=>'请在应用收银台配置支付宝设置']);die;
}
if($aliConfig['aliPay']==2){
echo json_encode(['code'=>2,'msg'=>'请在应用收银台开启支付宝支付']);die;
}
$config =array(
'app_id' =>$aliConfig['aliAppId'],
'ali_public_key' =>$aliConfig['publicKey'],
'private_key' =>$aliConfig['privateKey'],
);
// $config =array(
// 'app_id' => '2019091867562464',
// 'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjEKdm/ZchS/TmkEim2qrTfSFv4kq44KILM+7NaqsJTzrfZwWAWLeEqCHCM9n2lB/3cU0ImLPpHlzFLoy0hKgk+ZtbXhgfTLHtSErQL+WLqsNMe7mcrUYGO/9/51Z8X/b5UJgUzlVWoxnlROCfoGTQCmSmof5RtInWyXWk0CCj3u9jyzXsLhaonB3o1Y5rJEXyrQwCTyAgZlw9UesaKtq+l6J3ry2tHJSKt6tfH4nLA2F8CTteSOjmVd6y5RebqRhud6hBlVxoSV7FS7wTLVR3su8rgH6AAydB12IRd+TnGYYk5trNsqF2CLCk8sKcktL7OkUFiAHFooqcLqJpqTYCwIDAQAB',
// 'private_key' => 'MIIEpgIBAAKCAQEA6l/HNl169TQ+cwm80tHgoHF+FJtC5b26/Xw7dwy8UJiBB1p1WO1p9Si01WdSQbBwZcxUY+A347LE2R9FH70kc6d5Fan7vZTUAT+a6xF7+TwZshyTlNM2zB2/a07wXZqkrjuwIQ5AnqqbGhbyq6tqD4+H2J59SHgK21ZJpmbGoqDfOGJC79n8sGD2X9BGU9JS5STwqQN6lqY0/FhyQZmcv6EYFapXXIUzzDZ/bZeGvRa9JAqTylI+Kd96aAYZtrkZCkuysjgdvwTA02w4nA0xDKMen4iu3GsDo+pSQFfYSdsxTdnuYcEfs6AV7Y/tc6fLrb4mTELJK8AS3wd/WAKKZwIDAQABAoIBAQC1gODkwDYVqJToP9VEKpbbiajLSoXfJzSlU801X96CR+g8ipgv+wRAgHqyfWZdSsdwfnGoOx7tLid1wdqlPrP5AOwrk81JvvUD1n8hphOtKxb3MVw1N/DK2ArCjopk4vq/l6fJoaD3f0XISZc6zO/BBzV70xlQwu4deFBnFlaj35g2/zK5GRCbs6Sjka3WqEC9Dd16jJXfV4Zal2Mmv1eyaYGnyBAc3gdftA3RRqffJ5RsisgiY2KKaNg20kPW7um3U2pcYAxSYZhJVEsd4r0paKPG9jtkSrR+zEzyR1pHZDmD3DAS5sggpiPdLiMYyYEBOKzCLumCvqdPFiX+XGJpAoGBAPcYAkfX0i893dGfHbbMSeoxGTJkI7y0YqmhFaJVgYBD4HkkWUHUbfqcAmJW5lw2Ain/jRnRBhEyuLeAaTpPTpNtRtyCagfdD4ULpLE2R89tPttcDgZ5uLq3Tdg88IKbdA9A0I6RnUomglJbbwSFrl+5PxUb+0iFlfaQUj8cmDU7AoGBAPLSZvFpscsISy7s7AkQVOrfiufgDa+MjwEzIcZp3qrjTOkLCvE4Ta12/ABKYtD8o7OR7fhfGUbRMW5vFpEauQdyFqN+xwZ9unJq83mv28qwbSY/TC4it6XSoq6cDgwhYloLWnj+D8Yejf8IiY1Ui/t23wZmbb96tZPywgmBu3zFAoGBAOBNZySYgjBoVMhJTMv3vtFdKKZZyScwCLA7jkwCmsA43biainv7vqpUnMVwZUUnsec2GHxrBrrt9Eh/xQYtoAKsnDroGCBzR/dajnJf9+gQH5M5iXHPZSX56Cx3hUzKmRyPlcMV5Fa/hmYEok7Um2pB20XqVL2MpolgkYjBCFqpAoGBAJLjnqx5ULlOihSX8+1DuOrgUaoVSpIgiD2kjdD2KGHd4J+1M2has/q0WJtgZEiiG/E73OX7uVGyqKFyiAc9UCLl7DX5MjKGCiy+8AxzypThhxW1AsOB8vBX7FuOQZ0q8NEhvxgkMKybvTBDHNqnA4saDK5Vdhx4AbG/D4wqs501AoGBAPKLLch4WckE9m+awheuuTp50ON8ghjwMvJg3u9DgDQber/8C9ig1nN1SQp9vXYSWW9sc70YvGpwBbD+V+XZD3yTbEiyt5ESVsFMhE19C2oBg9Dy64lJ8B4i1uJ9EhTeP3A8XjP2f0r8ClQwQoh0OL6rx7734ToZnUnnWOhxZ9Eh',
// );
$order = [
'out_trade_no' =>$outTradeNo,
'total_amount' =>$money,
'subject' => '收银台-支付宝当面付',
'auth_code' =>$auth_code,
];
try {
$alipay = Pay::alipay($config)->pos($order);
}catch (\Exception $e){
$message= $e->getMessage();
$ISUSERPAYING = strpos($message,'order success pay inprocess');
if($ISUSERPAYING){
$data=[
'code'=>'USERPAYING',
'outTradeNo'=>$outTradeNo,
'payModel'=>2
];
}else{
$data=[
'code'=>'ERROR',
'outTradeNo'=>$outTradeNo,
'payModel'=>2
];
}
echo json_encode(['code'=> empty($ISUSERPAYING) ? 2:1,'msg'=>empty($ISUSERPAYING) ? $e->getMessage():'等待用户支付','data'=>$data]);die;
}
if(!$alipay){
echo json_encode(['code'=>2,'msg'=>'订单异常,请重新下单']);die;
}
switch ($alipay->code) {
case "10000":
$payStatus=1;
break;
case "10003":
$payStatus=2;
break;
case "40004":
$payStatus=2;
//echo json_encode(['code'=>2,'msg'=>'支付失败']);die;
break;
default:
$payStatus=2;
//echo json_encode(['code'=>2,'msg'=>'不支持的交易状态,交易返回异常!!!']);die;
break;
}
}else{
$payType=1;
$money=bcmul($money,100,0);
$order = [
'out_trade_no' =>$outTradeNo,
'total_fee' =>$money,
'body' => '收银台-微信当面付',
'auth_code' =>$auth_code,
];
$config=WeChat::getWxPayConfig($uniacid,1,$storeId);
if($config['sub_mch_id']){
$order['sub_mch_id']=$config['sub_mch_id'];
}
try {
$wechat = Pay::wechat($config)->pos($order);
}catch (\Exception $e){
$message= $e->getMessage();
$ISUSERPAYING = strpos($message,'USERPAYING');
if($ISUSERPAYING){
$data=[
'code'=>'USERPAYING',
'outTradeNo'=>$outTradeNo,
'payModel'=>1
];
}else{
$data=[
'code'=>'ERROR',
'outTradeNo'=>$outTradeNo,
'payModel'=>1
];
}
echo json_encode(['code'=> empty($ISUSERPAYING) ? 2:1,'msg'=>empty($ISUSERPAYING) ? $e->getMessage():'等待用户支付','data'=>$data]);die;
}
if($wechat->return_code=='SUCCESS'&&$wechat->return_msg=='OK'&&$wechat->result_code=='SUCCESS'){
$payStatus=1;
}
if($payStatus){
//服务商分账
if($order['sub_mch_id']){
$storeSet=Config::getStoreSet('serviceCharge',$storeId);//商户子商户号设置
if($storeSet['sonService']==1 AND $storeSet['subMchId']){
$orderId=(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where(['out_trade_no' =>$outTradeNo])
->one()['id'];
if($orderId){
WeChat::profitSharing($orderId,2);
}
}
}
}
}
return $payStatus;
}
//餐桌模式落单 存储Order_goods
public function actionSetOrder(){
$request = Yii::$app->request;
if ($request->isPost) {
//echo json_encode(['code' =>1, 'msg' => '功能待完善中,敬请期待...']);die;
$result = axios_request();
$userId = $result['userId']?:0;
$storeId = $result['storeId'] ?: $this->shop_id;
$uniacid = $this->wqData['uniacid'];
if (!$storeId) {
echo json_encode(['code' => 2, 'msg' => '无效的门店']);
die;
}
$session = new Session;
$session->open();
$tableId = $result['tableId'] ?: 0;
if (!$tableId) {
echo json_encode(['code' => 2, 'msg' => '无效的桌台']);
die;
}
$operatorId = Yii::$app->session->get('userInfo')['id'];
if (!$operatorId) {
return $this->result(2, '请用收银员账号登录');
}
$carData = (new \yii\db\Query())
->from('{{%ybwm_cashier_goods}}')
->where(['tableId' => $tableId, 'state' => 1, 'storeId' => $storeId, 'uniacid' => $uniacid,'operatorId'=>$operatorId])
->all();
if (!$carData) {
echo json_encode(['code' => 2, 'msg' => '无效的请求']);
die;
}
$payModeData=Config::getStoreSet('instoreSet',$storeId);
$eatType=$payModeData['payMode']?:2;;
if($tableId){
if($eatType==1){
$state=1;
}else{
$state=2;
}
}
$orderInfo=(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('tableId=:tableId',[':tableId'=>$tableId])
->andWhere(['<=','state',$state])
->orderBy('id desc')->one();
$orderId =$orderInfo['id'];
$orderOne=(new \yii\db\Query())
->from('{{%ybwm_order_goods}}')
->where(['orderId' =>$orderId,'item'=>2])->orderBy('id desc')
->one();
if ($orderOne) {
$orderId =$orderInfo['id'];
$addType=1;
$addNum=$orderOne['addNum']+1;
}else{
$addType=2;
$addNum=0;
}
$transaction = Yii::$app->db->beginTransaction();
//保存就餐人数 服务费
$storeSet = Config::getStoreSet('instoreSet', $result['storeId']);
if($storeSet['serviceType']==2){//按桌台收取
$tablewareNum=1;
}else{
//按人数收取
$tablewareNum=$result['number'];
}
//serviceMoney 餐桌费用 number就餐人数
$tablewareMoney=bcmul($result['serviceMoney'],$tablewareNum,2);
if($eatType==1){
Yii::$app->db->createCommand()->update('{{%ybwm_instore_order}}', ['state'=>$state,'people' =>$result['number'],'tablewareNum' =>$tablewareNum,'tablewareMoney'=>$tablewareMoney], ['id' =>$orderId])->execute();
//修改桌台就餐人数
Yii::$app->db->createCommand()->update('{{%ybwm_table}}', ['selStatus'=>0,'state'=>2,'people' =>$result['number']], ['id' =>$tableId])->execute();
}else{
Yii::$app->db->createCommand()->update('{{%ybwm_instore_order}}', ['receiptAt'=>time(),'state'=>$state,'people' =>$result['number'],'tablewareNum' =>$tablewareNum,'tablewareMoney'=>$tablewareMoney], ['id' =>$orderId])->execute();
//修改桌台就餐人数
Yii::$app->db->createCommand()->update('{{%ybwm_table}}', ['selStatus'=>0,'state'=>3 ,'people' =>$result['number']], ['id' =>$tableId])->execute();
}
//var_dump($carData);die;
try{
foreach ($carData as $v) {
$goodsData = array(
'orderId' => $orderId,
'goodsId' => $v['goodsId'],
'name' => $v['name'],
'money' => $v['money'],
'num' => $v['num'],
'data' => $v['groupName'],
'icon' => $v['icon'],
'storeId' => $v['storeId'],
'uniacid' => $v['uniacid'],
'createdAt' => time(),
'groupId' => $v['groupId']?:0,
'material' => $v['materialName'],
'attribute' => $v['attribute'],
'item'=>2,
'addType'=>$addType,
'addNum'=>$addNum
);
YII::$app->db->createCommand()->insert('{{%ybwm_order_goods}}', $goodsData)->execute();
$comboGoodsArr=(new \yii\db\Query())->from('{{%ybwm_core_goods}}')->select('comboGoodsArr')->where(['id'=>$v['goodsId']])->one();
if($comboGoodsArr = json_decode($comboGoodsArr['comboGoodsArr'],true)){
foreach ($comboGoodsArr as $j){
$discountOrderGoodOne['groupId'] = 0;
$discountOrderGoodOne['goodsId'] = $j['id'];
$discountOrderGoodOne['attribute'] = '';
$discountOrderGoodOne['data'] = '';
$discountOrderGoodOne['material'] = '';
$discountOrderGoodOne['orderId'] = $orderId;
$discountOrderGoodOne['name'] = $j['name'];
$discountOrderGoodOne['num'] = $j['num'];
$discountOrderGoodOne['icon'] = $j['icon'];
$discountOrderGoodOne['storeId'] = $j['storeId'];
$discountOrderGoodOne['uniacid'] = $uniacid;
$discountOrderGoodOne['createdAt'] = time();
$discountOrderGoodOne['item'] = 2;
$discountOrderGoodOne['isActivity'] = 0;
$discountOrderGoodOne['money'] = 0;
$discountOrderGoodsResOne=Yii::$app->db->createCommand()->insert('{{%ybwm_order_goods}}', $discountOrderGoodOne)->execute();
if(!$discountOrderGoodsResOne){
$transaction->rollBack();//事务回滚
return $this->result(2, '下单失败','订单商品表插入失败');
}
}
}
}
$orderGoodsData=(new \yii\db\Query())
->from('{{%ybwm_order_goods}}')
->where(['orderId' =>$orderId,'item'=>2])
->andWhere(['<','addType',3])
->all();
$money = 0;
$originMoney = 0;
$goodsNum = 0;
foreach ($orderGoodsData as $k=>$v){
$goodMoney=0;$materMoney=0;
$goodMoney=bcmul($orderGoodsData[$k]['money'],$orderGoodsData[$k]['num'],2);
$materMoney=bcmul($orderGoodsData[$k]['materialMoney'],$orderGoodsData[$k]['num'],2);
$originMoney+=bcadd($goodMoney,$materMoney,2);
$goodsNum+=$orderGoodsData[$k]['num'];
}
$money=bcadd($originMoney,$tablewareMoney,2);
$orderData = array(
'money' => $money,
'originMoney' => $originMoney,
'goodsNum' => $goodsNum,
);
YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', $orderData, ['id' => $orderId])->execute();
YII::$app->db->createCommand()->delete('{{%ybwm_cashier_goods}}', ['tableId'=>$tableId])->execute();
$transaction->commit();//提交事务会真正的执行数据库操作
if($addType==1){
$addGoods=(new \yii\db\Query())
->select('id')
->from('{{%ybwm_order_goods}}')
->where(['orderId' =>$orderId,'addType'=>1,'addNum'=>$addNum,'item'=>2])
->all();
Printing::instoreOrderPrint($orderId,2,array_column($addGoods,'id'));
}else{
Printing::orderPrint($orderId,2);
}
} catch (Exception $e) {
$transaction->rollback();
echo "insert data error:", $e->getMessage();die;
}
echo json_encode(['code' => 1, 'msg' => '成功', 'orderId' => $orderId]);die;
}
}
//餐台商品改价
/**
* @return bool
*/
public function actionPutMoney(){
$result=axios_request();
if($result['money']&&$result['orderId']){
$orderInfo=(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where(['id'=>$result['orderId']])
->one();
$money=bcsub($orderInfo['money'],$result['money'],2);
YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}',['money'=>$money,'discount'=>$result['money']], ['id'=>$result['orderId']])->execute();
return $this->result(1, '成功');
}
}
//打印订单小票
public function actionHandleOrder(){
$result = axios_request();
$tableId=$result['tableId'];
$orderId=$result['orderId'];
if($tableId){
$order =(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('tableId=:tableId',[':tableId'=>$tableId])
->andWhere(['<=','state',2])
->orderBy('id desc')->one();
if(!$order){
echo json_encode(['code' =>2, 'msg' => '该桌台暂未下单']);die;
}
$orderId=$order['id'];
}
$result=axios_request();
$result['type']=$result['type']?:'print';
if($result['type']=='refund'){
if($tableId){
$res=Order::inStoreRefund($result['orderId']);
}else{
//快餐退款
$res=Order::fastCancel($result['orderId']);
}
if(!$res){
return $this->result(2,'失败');
}
}
if($result['type']=='receipt'){
//快餐接单
$res=Order::fastReceipt($orderId);
Printing::orderPrint($orderId,3);
if(!$res){
return $this->result(2,'失败');
}
}
if($result['type']=='print'){
if($tableId){
Printing::orderPrint($orderId,2);
}else{
Printing::orderPrint($orderId,3);
}
//Printing::orderPrint($orderId,3,'',false);
}
if($result['type']=='rejection'){
//快餐拒单
$res=Order::fastRejection($orderId);
if(!$res){
return $this->result(2,'失败');
}
}
if($result['type']=='confirm'){
//完成
$res=Order::fastComplete($orderId);
if(!$res){
return $this->result(2,'失败');
}
}
if($result['type']=='call'){
//呼叫
$res=Order::fastCall($orderId);
// $returnPath='/web/static/music/' . date('Ymd') . '/fast1.mp3';
// if(Yii::$app->params['isDev']==true){
// $res=Yii::$app->request->hostInfo.'/addons/yb_wm/'.$returnPath;
// }else{
// $res=Yii::$app->request->hostInfo.'/'.$returnPath;
// }
return $this->result(1,'成功',$res);
}
echo json_encode(['code' => 1, 'msg' => '成功']);die;
}
//整单取消
public function actionDelLine(){
$result = axios_request();
$tableId=$result['tableId'];
$order =(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('tableId=:tableId AND state=2',[':tableId'=>$tableId])->orderBy('id desc')->one();
$transaction = Yii::$app->db->beginTransaction();
try{
YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', ['state'=>4],['id' => $order['id']])->execute();
YII::$app->db->createCommand()->update('{{%ybwm_table}}', ['state'=>1,'people'=>0],['id' =>$tableId])->execute();
$transaction->commit();//提交事务会真正的执行数据库操作
} catch (Exception $e) {
$transaction->rollback();
echo json_encode(['code' => 2, 'msg' =>$e->getMessage()]);die;
}
echo json_encode(['code' =>1, 'msg' =>'成功']);die;
}
//抹零
public function actionChangeMoney(){
$result = axios_request();
$tableId=$result['tableId'];
$uniacid = $this->wqData['uniacid'];
$money= $result['money'];
$fracture=$result['fracture'];
$storeId = $result['storeId'] ?: $this->shop_id;
$type=$result['type']?:'goZero';
if($tableId){
$payModeData=Config::getStoreSet('instoreSet',$storeId);
$eatType=$payModeData['payMode']?:2;
$order =(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('tableId=:tableId',[':tableId'=>$tableId])
->andWhere(['eatType'=>$eatType])
->andWhere(['<','state',3])->orderBy('id desc')->one();
if (!$order) {
echo json_encode(['code' => 2, 'msg' => '无效的请求']);
die;
}
$orderId=$order['id'];
}else{
$operatorId = Yii::$app->session->get('userInfo')['id'];
if (!$operatorId) {
return $this->result(2, '请用收银员账号登录');
}
$carData = (new \yii\db\Query())
->from('{{%ybwm_cashier_goods}}')
->where(['state' => 1,'storeId' => $storeId,'uniacid' => $uniacid,'operatorId'=>$operatorId])
->one();
if (!$carData) {
echo json_encode(['code' => 2, 'msg' => '无效的请求']);
die;
}
$orderId=$carData['orderId'];
if(!$orderId){
echo json_encode(['code' => 2, 'msg' => '数据异常']);
die;
}
$order =(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('id=:id',[':id'=>$orderId])->orderBy('id desc')->one();
}
$orderMoney=bcadd($order['tablewareMoney'],$order['originMoney'],2);
//var_dump($order['money']);var_dump($money);die;
if($type=='changePrice'){
$discount=bcsub($orderMoney,$money,2);
$newMoney=$money;
}
if($type=='discount'){
$newMoney=bcmul($orderMoney,bcdiv($fracture,10,2),2);
$discount=bcsub($orderMoney,$newMoney,2);
}
if($type=='goZero'){
//$cashierSetConfig=Config::getSystemSet('cashierSet',$this->wqData['uniacid']);
//if($cashierSetConfig['discountStatus']==1&&$cashierSetConfig['discountAuto']==2){
switch ($result['discountType']){
case 1;
$newMoney=substr($orderMoney,0,strlen($orderMoney)-1);
break;
case 2;
$newMoney=intval($orderMoney);
break;
case 3;
$newMoney=round($orderMoney,1);
break;
case 4;
$newMoney=round($orderMoney);
break;
}
$discount=bcsub($orderMoney,$newMoney,2);
}
$upData=['discount'=>$discount,'money'=>$newMoney];
YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}', $upData,['id' =>$orderId])->execute();
echo json_encode(['code' =>1, 'msg' =>'成功']);die;
}
//餐桌转台
public function actionTurntable(){
$result=axios_request();
$tableId=$result['tableId'];
$storeId=$result['storeId']?: $this->shop_id;
$toTableId=$result['toTableId'];
$payModeData=Config::getStoreSet('instoreSet',$storeId);
$eatType=$payModeData['payMode']?:2;
if($eatType==1){
echo json_encode(['code'=>2,'msg'=>'餐前模式不可转台!']);die;
}
$toTableIdInfo=(new \yii\db\Query())
->from('{{%ybwm_table}}')
->where('id=:id',[':id'=>$toTableId])
->one();
if($toTableIdInfo){
$toOrderInfo=(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('tableId=:tableId',[':tableId'=>$toTableId])
->andWhere(['eatType'=>2,'state'=>2])
->orderBy('id desc')
->one();
if($toOrderInfo){
echo json_encode(['code'=>2,'msg'=>'转台失败,不可转到已就餐的桌台!']);die;
}
}else{
echo json_encode(['code'=>2,'msg'=>'桌台不存在']);die;
}
$transaction = Yii::$app->db->beginTransaction(); //开始事务
try{
$tableIdInfo=(new \yii\db\Query())
->from('{{%ybwm_table}}')->where(['id'=>$tableId])->one();
$order =(new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where('tableId=:tableId',[':tableId'=>$tableId])
->andWhere(['eatType'=>2,'state'=>2])
->orderBy('id desc')->one();
if(!$order){
echo json_encode(['code'=>2,'msg'=>'无效的订单']);die;
}
if($order['eatType']==2&&$order['state']<>2){
echo json_encode(['code'=>2,'msg'=>'就餐中才能转台']);die;
}
$tableTypeData=(new \yii\db\Query())
->from('{{%ybwm_table_type}}')
->where('id=:id',[':id'=>$toTableIdInfo['typeId']])
->one();
$instoreData=['number'=>$toTableIdInfo['name'],'typeName'=>$tableTypeData['name'].'('.$tableTypeData['minNum'].'-'.$tableTypeData['maxNum'].')','tableId'=>$toTableId];
YII::$app->db->createCommand()->update('{{%ybwm_instore_order}}',$instoreData,['id'=>$order['id']])->execute();
YII::$app->db->createCommand()->update('{{%ybwm_table}}', ['state'=>1,'userId'=>'','people'=>0],['id' =>$result['tableId']])->execute();
YII::$app->db->createCommand()->update('{{%ybwm_shop_car}}', ['tableId'=>$toTableId],['tableId'=>$tableId])->execute();
YII::$app->db->createCommand()->update('{{%ybwm_cashier_goods}}', ['tableId'=>$toTableId],['orderId'=>$order['id']])->execute();
$array=['people'=>$tableIdInfo['people'],'changeAt'=>time(),'userId'=>$tableIdInfo['userId'],'state'=>$tableIdInfo['state'],'addNum'=>$tableIdInfo['addNum']];
YII::$app->db->createCommand()->update('{{%ybwm_table}}',$array,['id' =>$toTableId])->execute();
$transaction->commit();//提交事务
}catch(\Exception $e){// 如果有一条查询失败,则会抛出异常
//var_dump($e->getMessage());
$transaction->rollBack();//事务回滚
}
echo json_encode(['code'=>1,'msg'=>'成功']);die;
}
//获取桌台区域
public function actionTableArea(){
$result=axios_request();
$storeId=$result['storeId']?: $this->shop_id;
$data =(new \yii\db\Query())
->from('{{%ybwm_table_area}}')
->where('storeId=:storeId and display=1 and deleteAt=0',[':storeId'=>$storeId])
->orderBy('id desc')->all();
echo json_encode(['code'=>1,'msg'=>'成功','data'=>$data]);die;
}
//获取桌台类型
public function actionTableType(){
$result=axios_request();
$storeId=$result['storeId']?: $this->shop_id;
$data=(new \yii\db\Query())
->from('{{%ybwm_table_type}}')
->where('storeId=:storeId and display=1 and deleteAt=0',[':storeId'=>$storeId])
->orderBy('id desc')->all();
echo json_encode(['code'=>1,'msg'=>'成功','data'=>$data]);die;
}
//获取桌台类型下的餐桌
public function actionChangeTableList(){
$result=axios_request();
$storeId=$result['storeId']?: $this->shop_id;
$areaId=$result['areaId'];
$typeId=$result['typeId'];
$data=(new \yii\db\Query())
->from('{{%ybwm_table}}')
->where('storeId=:storeId and display=1 and state=1 and deleteAt=0 and typeId=:typeId and areaId=:areaId',[':storeId'=>$storeId,':typeId'=>$typeId,':areaId'=>$areaId])
->orderBy('id asc')->all();
echo json_encode(['code'=>1,'msg'=>'成功','data'=>$data]);die;
}
//查询支付订单
public function actionQueryOrder()
{
$result = axios_request();
$outTradeNo = $result['outTradeNo'];
$payMode = $result['payModel'];
$order = (new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where(['outTradeNo' => $outTradeNo])
->one();
if ($order['state'] == 2) {
echo json_encode(['code' => 1, 'msg' => '成功','state'=>'SUCCESS']);
die;
}
if ($order['state'] == 1) {
$uniacid = $order['uniacid'];
$aliConfig = Config::getSystemSet('cashierSet', $uniacid);
$config = array(
'app_id' => $aliConfig['aliAppId'],
'ali_public_key' => $aliConfig['publicKey'],
'private_key' => $aliConfig['privateKey'],
);
if($payMode == 2){
try{
$alipay = Pay::alipay($config)->find($order['outTradeNo']);
if ($alipay->msg == 'Success' && $alipay->code == 10000) {
if($alipay->trade_status == 'TRADE_SUCCESS'){
YII::$app->db->createCommand()->delete('{{%ybwm_cashier_goods}}', ['tableId' => $order['tableId'], 'state' => 1, 'storeId' => $order['storeId'], 'uniacid' => $uniacid])->execute();
CallbackOrder::payOrder($order['id'], 2, $order['userId']);
echo json_encode(['code' => 1, 'msg' => '支付宝支付成功','state'=>'SUCCESS']); die;
}elseif($alipay->trade_status == 'WAIT_BUYER_PAY'){
echo json_encode(['code' => 1, 'msg' => '等待用户支付','state'=>'USERPAYING']);die;
}else{
echo json_encode(['code' => 2, 'msg' => '支付宝支付失败','state'=>'ERROR']); die;
}
}
}catch (\Exception $e){
echo json_encode(['code' => 2, 'msg' => $e->getMessage(),'state'=>'ERROR']); die;
}
}elseif($payMode == 1){
$config = WeChat::getWxPayConfig($uniacid, 1, $order['storeId']);
try {
if ($config['sub_mch_id']) {
$order['sub_mch_id'] = $config['sub_mch_id'];
$order['out_trade_no'] = $order['outTradeNo'];
$wechat = Pay::wechat($config)->find($order);
} else {
$wechat = Pay::wechat($config)->find($order['outTradeNo']);
}
if ($wechat->return_code == 'SUCCESS' && $wechat->return_msg == 'OK' && $wechat->result_code == 'SUCCESS') {
if($wechat->trade_state == 'SUCCESS'){
if ($config['sub_mch_id']) {
$storeSet = Config::getStoreSet('serviceCharge', $order['storeId']);//商户子商户号设置
if ($storeSet['sonService'] == 1 and $storeSet['subMchId']) {
$orderId = (new \yii\db\Query())
->from('{{%ybwm_instore_order}}')
->where(['outTradeNo' => $order['outTradeNo']])
->one()['id'];
}
}
YII::$app->db->createCommand()->delete('{{%ybwm_cashier_goods}}', ['tableId' => $order['tableId'], 'state' => 1, 'storeId' => $order['storeId'], 'uniacid' => $uniacid])->execute();
CallbackOrder::payOrder($order['id'], 1, $order['userId']);
echo json_encode(['code' => 1, 'msg' => '微信支付成功','state'=>'SUCCESS']);
die;
}elseif($wechat->trade_state == 'USERPAYING'){
echo json_encode(['code' => 1, 'msg' => $wechat->trade_state_desc,'state'=>'USERPAYING']);die;
}else{
echo json_encode(['code' => 2, 'msg' => $wechat->trade_state_desc,'state'=>'error']);die;
}
}
} catch (\Exception $e) {
echo json_encode(['code' => 2, 'msg' => $e->getMessage()]);
die;
}
}
}
echo json_encode(['code' => 2, 'msg' => '订单状态错误'],320);
die;
}
}