adminOperateLogger = new AdminOperate([ 'fetchClass' => Order::class, ]); } /** * @inheritdoc */ public function rules() { return [ [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress'], 'trim'], [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress'], 'required'], [['status'], 'isStatus'], [['addressId'], 'isAddress'], [['payType'], 'isPayType'], [['payPassword'], 'validatePassword'], ]; } public function attributeLabels() { return [ 'sn' => '订单号', 'expressCompany' => '快递公司', 'orderTrackNo' => '快递单号', 'status' => '状态', 'remark' => '备注', 'type' => '订单类型', 'addressId' => '收货地址', 'payType' => '支付方式', 'goodsId' => '商品ID', 'goodsNum' => '商品数量', 'userName' => '复消会员编号', 'consignee' => '收货人', 'acceptMobile' => '收货电话', 'province' => '省', 'city' => '市', 'county' => '区', 'detailaddress' => '收货详细地址', ]; } /** * 指定校验场景 * @return array */ public function scenarios() { $parentScenarios = parent::scenarios(); $customScenarios = [ // 管理员发货 'adminDelivery' => ['sn', 'expressCompany', 'orderTrackNo'], // 会员确认收货 'userConfirm' => ['sn', 'expressCompany', 'orderTrackNo'], // 管理员修改订单状态 'adminStatus' => ['sn', 'status'], // 管理员修改备注 'adminRemark' => ['sn', 'remark'], // 会员下单 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword'], // 帮会员复消下单 'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','city','county','detailaddress'], ]; return array_merge($parentScenarios, $customScenarios); } /** * 校验之前 * @return bool */ public function beforeValidate() { $parentValidate = parent::beforeValidate(); if ($this->sn) { $this->_model = Order::findOne(['SN'=>$this->sn]); if (!$this->_model){ $this->addError('sn', '订单不存在'); return false; } } if ($this->scenario == 'adminDelivery'){ if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['cancel']) { $this->addError('sn', '订单已取消不能发货'); return false; } if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) { $this->addError('sn', '订单已删除不能发货'); return false; } } return $parentValidate; } /** * 校验支付密码 * @param $attribute * @param $params */ public function validatePassword($attribute, $params) { if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) { $this->addError($attribute, '支付密码不正确'); } } /** * 判断收货地址是否存在 * @param $attribute */ public function isAddress($attribute){ if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) { $this->addError($attribute, '收货地址不存在'); } else { $this->_address = $receiveAddress; } } /** * 判断支付方式 * @param $attribute */ public function isPayType($attribute){ if(!array_key_exists($this->payType, ShopGoods::payTypes())){ $this->addError($attribute, '支付方式错误1'); return; } // 一个订单只能包含一类商品 $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all(); $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE')); if (count($goodsCategoryType) != 1) { $this->addError($attribute, '订单不能包含多种商品分类'); return; } // 购买方式 $sellTypeLabelMap = array_column(ShopGoods::SALE_TYPE, NULL, 'label'); if (!array_key_exists($this->payType, $sellTypeLabelMap)) { $this->addError($attribute, '支付方式错误2'); return; } // 所选支付方式必须是商品分类支持的类型 $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id'); // 商品类型 $currCategoryType = $goodsCategoryType[0]; if (!array_key_exists($currCategoryType, $categoryType)) { $this->addError($attribute, '商品分类错误'); return; } $sellType = $categoryType[$currCategoryType]['sell_type'] ?? []; if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) { $this->addError($attribute, '支付方式错误3'); return; } } /** * 校验类型 * @param $attribute */ public function isStatus($attribute){ if(!in_array($this->type, \Yii::$app->params['orderStatus'])){ $this->addError($attribute, '类型错误'); return ; } if ($this->scenario == 'adminStatus'){ if ($this->status == $this->_model['STATUS']) { $this->addError($attribute, '订单状态没有改变'); return ; } if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) { $this->addError($attribute, '订单已经进入物流状态不能改为未支付'); return ; } elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) { $this->addError($attribute, '订单已失效不能处理'); return ; } elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) { $this->addError($attribute, '订单不能单独处理为物流状态'); return ; } elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) { $this->addError($attribute, '订单已失效不能处理'); return ; } elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) { if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) { $this->addError($attribute, '订单已完成不能取消'); return ; } if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) { $this->addError($attribute, '订单已删除不能取消'); return ; } } elseif($this->status == \Yii::$app->params['orderStatus']['del']) { if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) { $this->addError($attribute, '订单已完成不能删除'); return ; } } } } /** * 管理员发货 * @return Order|null * @throws \yii\db\Exception */ public function adminDelivery(){ if(!$this->validate()){ return null; } $db = \Yii::$app->db; $transaction = $db->beginTransaction(); try { $period = Period::instance(); $this->_model->DELIVERY_STATUS = \Yii::$app->params['deliveryStatus']['delivered']['value']; $this->_model->DELIVERY_PERIOD = $period->getNowPeriodNum(); $this->_model->DELIVERY_AT = Date::nowTime(); $this->_model->EXPRESS_COMPANY = $this->expressCompany; $this->_model->ORDER_TRACK_NO = $this->orderTrackNo; $this->_model->STATUS = \Yii::$app->params['orderStatus']['delivery']['value']; if(!$this->_model->save()){ throw new Exception(Form::formatErrorsForApi($this->_model->getErrors())); } $transaction->commit(); } catch (Exception $e) { $transaction->rollBack(); $this->addError('edit', $e->getMessage()); return null; } return $this->_model; } /** * 复销 * @return bool|null * @throws Exception * @throws \yii\db\Exception */ public function add(){ if(!$this->validate()){ return null; } $ids = $this->goodsId; $totalAmount = 0; $totalPv = 0; $goodsType = ShopGoods::GOODS_TYPE; foreach ($this->goodsNum as $k => $v) { if ($v) { $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]); if($goods['STORE_NUMS']>0){ if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) { $discount = $goodsType[$goods['TYPE']]['discount']; $realPrice = $goods['SELL_PRICE'] * $discount/100; $realPv = $goods['PRICE_PV'] * $discount/100; } else { $discount = $goods['SELL_DISCOUNT']; $realPrice = $goods['SELL_PRICE'] * $discount; $realPv = $goods['PRICE_PV'] * $discount; } $totalAmount += $realPrice * intval($v); $totalPv += $realPv * intval($v); // if($this->payType=='cash') { // $discount = $goodsType[$goods['TYPE']]['discount']; // $realPrice = $goods['SELL_PRICE'] * $discount/100; // $realPv = $goods['PRICE_PV'] * $discount/100; // $totalAmount += $realPrice * intval($v); // $totalPv += $realPv * intval($v); // }else{ // $realPrice = $goods['SELL_PRICE']; // $realPv = $goods['PRICE_PV']; // $totalAmount += $realPrice * intval($v); // $totalPv += $realPv * intval($v); // } $this->_orderGoods[] = [ 'GOODS_ID' => $goods['ID'], 'PRICE' => $goods['SELL_PRICE'], 'PV' => $goods['PRICE_PV'], 'REAL_PRICE' => $realPrice, 'REAL_PV' => $realPv, 'POINT' => $goods['POINT'], 'BUY_NUMS' => intval($v), 'SKU_CODE' => $goods['GOODS_NO'], 'GOODS_TITLE' => $goods['GOODS_NAME'], 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'], 'PAY_TYPE' => $this->payType, ]; } } } $this->_decAmount = $totalAmount; $this->_decPv = $totalPv; $this->_freight = ($totalAmount>=300) ? 0 : 15; if($this->_address['PROVINCE']==1){ $this->_freight = 0; } $this->_payAmount = $this->_decAmount + $this->_freight; $db = \Yii::$app->db; $transaction = $db->beginTransaction(); try { //判断用户余额是否充足 $result = $this->getBalanceAdequate($this->payType, $this->_payAmount); if ($result['code'] !== 200) { throw new Exception($result['message']); } //写入订单 if (!$orderResult = $this->addOrder()) { throw new Exception(Form::formatErrorsForApi($orderResult->getErrors())); } $transaction->commit(); }catch (\Exception $e){ $transaction->rollBack(); $this->addError('add', $e->getMessage()); return null; } return true; } /** * 判断对应账户余额是否充足. * @param $payType string 支付方式. * @param $payAmount numeric 支付金额 * @return array|int[] */ public function getBalanceAdequate(string $payType, $payAmount): array { $loginUserId = \Yii::$app->user->id; if ($payType == 'cash') { if (Cash::getAvailableBalance($loginUserId) < $payAmount) { return ['code' => 500, 'message' => '余额不足,无法购买商品']; } } else if ($payType =='exchange') { if ($payAmount > Balance::getBalanceExchangePoints($loginUserId)) { return ['code' => 500, 'message' => '兑换积分不足,无法购买商品']; } } else if (in_array($payType, ['travel_points', 'car_points', 'house_points'])) { if ($payAmount > Balance::getAccountBalance($loginUserId, $payType)) { return ['code' => 500, 'message' => (Balance::BALANCE_TYPE[$payType]['title'] ?? '积分') . '不足,无法购买商品']; } } else{ if ($payAmount > Balance::getBalanceReconsumePoints($loginUserId)) { return ['code' => 500, 'message' => '复消积分不足,无法购买商品']; } } return ['code' => 200]; } /** * 复销订单 * @throws Exception */ public function addOrder(){ $periodObj = Period::instance(); $nowPeriodNum = $periodObj->getNowPeriodNum(); $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum); $userId = \Yii::$app->user->id; $userName = Info::getUserNameByUserId($userId); $userRealName = Info::getUserRealNameByUserId($userId); $userMobile = Info::getUserMobileByUserId($userId); // 加入订单信息 if ($this->_address['PROVINCE'] != 1) { $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库 if (!$warehouse) { throw new Exception('地区2暂时不支持配送,具体联系客服'); } }else{ $warehouse = '01'; } $_hasPV = in_array($this->payType, ['exchange', 'travel_points', 'car_points', 'house_points']) ? 0 : $this->_decPv; $ordNo = $this->_generateSn(); $orderModel = new Order(); $orderModel->SN = 'OS'.$ordNo; $orderModel->DEC_SN = 'DS'.$ordNo; $orderModel->ORDER_TYPE = $this->type; $orderModel->USER_ID = $userId; $orderModel->USER_NAME = $userName; $orderModel->ORDER_AMOUNT = $this->_decAmount; $orderModel->PV = $_hasPV; $orderModel->PAY_AMOUNT = $this->_payAmount; $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩 $orderModel->PAY_AT = Date::nowTime(); $orderModel->PAY_TYPE = $this->payType; $orderModel->PERIOD_NUM = $nowPeriodNum; $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH); $orderModel->FREIGHT = $this->_freight; $orderModel->PAY_FREIGHT = $this->_freight; $orderModel->CONSIGNEE = $this->_address['CONSIGNEE']; $orderModel->MOBILE = $this->_address['MOBILE']; $orderModel->PROVINCE = $this->_address['PROVINCE']; $orderModel->CITY = $this->_address['CITY']; $orderModel->COUNTY = $this->_address['COUNTY']; $orderModel->ADDRESS = $this->_address['ADDRESS']; $orderModel->FRONT_REMARK = $this->remark; $orderModel->WAREHOUSE = $warehouse; $orderModel->STATUS = 1; $orderModel->CREATED_AT = Date::nowTime(); $orderModel->CREATE_USER = $userName; if($this->_address['PROVINCE']==1){ $orderModel->EXPRESS_TYPE = 1; $orderModel->CONSIGNEE = $userRealName; $orderModel->MOBILE = $userMobile; $orderModel->PROVINCE = 1; $orderModel->CITY = 1; $orderModel->COUNTY = 1; $orderModel->ADDRESS = ''; } if(!$orderModel->save()){ $this->addErrors($orderModel->getErrors()); return false; } // 加入商品到订单商品表 foreach($this->_orderGoods as $key=>$value){ // 增加判断,如果订单是兑换券购买,则AR_ORDER_GOODS中的REAL_PV真实PV应该是0 if (in_array($orderModel->PAY_TYPE, ['exchange', 'travel_points', 'car_points', 'house_points'])) { $this->_orderGoods[$key]['REAL_PV'] = 0; } $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN; $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH); } OrderGoods::batchInsert($this->_orderGoods); //扣除会员余额/积分 if($this->payType=='cash') { Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']); } else if ($this->payType=='exchange') { Balance::changeUserBonus(\Yii::$app->user->id,'exchange_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_EXCHANGE,'REMARK' => '会员兑换积分兑换']); } else if ($this->payType == 'travel_points') { Balance::changeUserBonus(\Yii::$app->user->id, 'travel_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::TRAVEL_POINTS_EXCHANGE,'REMARK' => '会员旅游换积分兑换']); } else if ($this->payType == 'car_points') { Balance::changeUserBonus(\Yii::$app->user->id, 'car_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::CAR_POINTS_EXCHANGE,'REMARK' => '会员名车积分兑换']); } else if ($this->payType == 'house_points') { Balance::changeUserBonus(\Yii::$app->user->id, 'house_points', -abs($this->_payAmount), ['DEAL_TYPE_ID' => DealType::HOUSE_POINTS_EXCHANGE,'REMARK' => '会员豪宅积分兑换']); } else{ Balance::changeUserBonus(\Yii::$app->user->id,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE,'REMARK' => '会员复销积分兑换']); } return $orderModel; } /** * 帮会员复销 * @return bool|null * @throws Exception * @throws \yii\db\Exception */ public function reconsumeAdd(){ if(!$this->validate()){ return null; } $ids = $this->goodsId; $totalAmount = 0; $totalPv = 0; $goodsType = ShopGoods::GOODS_TYPE; foreach ($this->goodsNum as $k => $v) { if ($v) { $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]); if($goods['STORE_NUMS']>0){ if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) { $discount = $goodsType[$goods['TYPE']]['discount']; $realPrice = $goods['SELL_PRICE'] * $discount/100; $realPv = $goods['PRICE_PV'] * $discount/100; } else { $discount = $goods['SELL_DISCOUNT']; $realPrice = $goods['SELL_PRICE'] * $discount; $realPv = $goods['PRICE_PV'] * $discount; } $totalAmount += $realPrice * intval($v); $totalPv += $realPv * intval($v); $this->_orderGoods[] = [ 'GOODS_ID' => $goods['ID'], 'PRICE' => $goods['SELL_PRICE'], 'PV' => $goods['PRICE_PV'], 'REAL_PRICE' => $realPrice, 'REAL_PV' => $realPv, 'POINT' => $goods['POINT'], 'BUY_NUMS' => intval($v), 'SKU_CODE' => $goods['GOODS_NO'], 'GOODS_TITLE' => $goods['GOODS_NAME'] ]; } } } $this->_decAmount = $totalAmount; $this->_decPv = $totalPv; $this->_freight = ($totalAmount>=300) ? 0 : 15; if($this->_address['PROVINCE']==1){ $this->_freight = 0; } $this->_payAmount = $this->_decAmount + $this->_freight; $db = \Yii::$app->db; $transaction = $db->beginTransaction(); try { $loginUserId = \Yii::$app->user->id; //是否开启伞下会员限制 $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE']; if($isResaleUmbrella){ $userId = Info::getUserIdByUserName($this->userName); $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count(); if(!$userNetwork){ throw new Exception($this->userName.'不是您的伞下会员,不能为其复消!'); } } //判断用户余额是否充足 if($this->payType=='cash') { if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) { throw new Exception('余额不足,无法购买商品'); } }else{ if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) { throw new Exception('复消积分不足,无法购买商品'); } } //写入订单 if (!$orderResult = $this->addUserOrder()) { throw new Exception(Form::formatErrorsForApi($orderResult->getErrors())); } $transaction->commit(); }catch (\Exception $e){ $transaction->rollBack(); $this->addError('add', $e->getMessage()); return null; } return true; } /** * 帮会员复消的订单 */ public function addUserOrder(){ $periodObj = Period::instance(); $nowPeriodNum = $periodObj->getNowPeriodNum(); $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum); //帮复消会员Id(登陆会员) $loginUserId = \Yii::$app->user->id; $loginUserName = Info::getUserNameByUserId($loginUserId); //订单会员Id $userId = Info::getUserIdByUserName($this->userName); // 加入订单信息 if($this->province!=1){ $warehouse = Region::getWarehouseByCode($this->province);//仓库 if(!$warehouse){ throw new Exception('地区1暂时不支持配送,具体联系客服'); } }else{ $warehouse = '01'; } $ordNo = $this->_generateSn(); $orderModel = new Order(); $orderModel->SN = 'OS'.$ordNo; $orderModel->DEC_SN = 'DS'.$ordNo; $orderModel->ORDER_TYPE = $this->type; $orderModel->USER_ID = $userId; $orderModel->USER_NAME = $this->userName; $orderModel->ORDER_AMOUNT = $this->_decAmount; $orderModel->PV = $this->_decPv; $orderModel->PAY_AMOUNT = $this->_payAmount; $orderModel->PAY_PV = $this->_decPv; $orderModel->PAY_AT = Date::nowTime(); $orderModel->PAY_TYPE = $this->payType; $orderModel->PERIOD_NUM = $nowPeriodNum; $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH); $orderModel->FREIGHT = $this->_freight; $orderModel->PAY_FREIGHT = $this->_freight; $orderModel->CONSIGNEE = $this->consignee; $orderModel->MOBILE = $this->acceptMobile; $orderModel->PROVINCE = $this->province; $orderModel->CITY = $this->city; $orderModel->COUNTY = $this->county; $orderModel->ADDRESS = $this->detailaddress; $orderModel->FRONT_REMARK = $this->remark; $orderModel->WAREHOUSE = $warehouse; $orderModel->STATUS = 1; $orderModel->CREATED_AT = Date::nowTime(); $orderModel->CREATE_USER = $loginUserName; if(!$orderModel->save()){ $this->addErrors($orderModel->getErrors()); return false; } // 加入商品到订单商品表 foreach($this->_orderGoods as $key=>$value){ $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN; $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH); } OrderGoods::batchInsert($this->_orderGoods); //扣除会员余额/积分 if($this->payType=='cash') { Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']); }else{ Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销积分兑换']); } return $orderModel; } /** * 生成流水号 * @return string */ private function _generateSn() { return Date::today('Ymd') . $this->_random(10, 1); } /** * 生成随机数 * @param $length * @param int $numeric * @return string */ private function _random($length, $numeric = 0) { $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35); $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed)); $hash = ''; $max = strlen($seed) - 1; for ($i = 0; $i < $length; $i++) { $hash .= $seed[mt_rand(0, $max)]; } return $hash; } }