trade_status == Order::ORDER_FLOW_CANCEL; } // 订单是否已确认收货 public static function isConfirm($order) { return $order->trade_status == Order::ORDER_FLOW_CONFIRM; } // 订单是否已发货 public static function isSend($order) { return $order->trade_status == Order::ORDER_FLOW_SEND; } // 订单是否已售后 public static function isAfterSale($order) { return $order->is_sale == 1; } // 获取系统配置的订单未支付自动取消时间 public static function getAutoCancelTime($store_id) { $name = \app\constants\OptionSetting::STORE_OVER_DAY; $data = \app\models\Option::get($name, $store_id, 'store', 0)['value']; if ($data > 0) { return $data * 86400; } return 0; } //分账 订单分账失败重新分账 public function profitSharing($order, $store_id) { $order_id_arr = []; try { $SharingReceiver = SharingReceiver::find()->where(['is_pay' => SharingReceiver::PAY_WAIT])->andWhere(['store_id' => $store_id, 'order_no' => $order->order_no])->groupBy('order_no')->asArray()->all(); foreach ($SharingReceiver as $item) { if ($item['execute_type'] == SharingReceiver::EXECUTE_TYPE_NORMAL) { // 微信 try { $order_id_arr = $this->wechatProfitSharing($order); } catch (\Exception $e) { \Yii::warning('---- COUPON BEHAVIOR END微信分账失败 ----'); } } if ($item['execute_type'] == SharingReceiver::EXECUTE_TYPE_ALIPAY) { // 支付宝 try { $this->alipayProfitSharing($order, $order_id_arr); } catch (\Exception $e) { \Yii::warning('---- COUPON BEHAVIOR END支付宝分账失败 ----'); } } } } catch (\Exception $e) { \Yii::warning('---- COUPON BEHAVIOR END ----'); } return $order_id_arr; } /** * 分账 * @param Order | \app\plugins\scanCodePay\models\Order | ReOrder | FoodOrder $order * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException * @throws \GuzzleHttp\Exception\GuzzleException */ public function wechatProfitSharing($order) { if (!\Yii::$app->isSaas()) { return; } if (!$order) { \Yii::error('<=======================> 微信分账订单不存在'); return; } if(in_array($order->pay_type, [Order::PAY_TYPE_WX_B2B])){ return $this->b2bProfitSharing($order); } if(in_array($order->pay_type, [Order::PAY_TYPE_ADAPAY_WX, Order::PAY_TYPE_ADAPAY_ALIPAY])){ return $this->adapayProfitSharing($order); } if(in_array($order->pay_type, [Order::PAY_TYPE_YUNST_WECHAT_PAY, Order::PAY_TYPE_YUNST_ALI_PAY])){ //通联支付分账 return $this->yunstProfitSharing($order); } // 此方法目前为多次分账,故分账结束后,剩余金额需要主动完结分账去触发解冻资金 $order_id = $order->order_no; $receivers_share = SharingReceiver::find()->where(['store_id' => $order->store_id, 'transaction_id' => $order->transaction_id, 'is_pay' => SharingReceiver::PAY_WAIT, 'execute_type' => SharingReceiver::EXECUTE_TYPE_NORMAL]) ->asArray()->all(); $profitOrderId = 0; $receivers_share_ok = SharingReceiver::find()->where(['store_id' => $order->store_id, 'transaction_id' => $order->transaction_id, 'is_pay' => SharingReceiver::PAY_SUCCESS, 'execute_type' => SharingReceiver::EXECUTE_TYPE_NORMAL]) ->orderBy('id DESC')->asArray()->one(); $receivers_share_ok && $profitOrderId = $receivers_share_ok['order_id']; $cacheKey = 'wechatProfitSharing11:' . $order->transaction_id; if(\Yii::$app->cache->get($cacheKey)){ \Yii::error('<=======================> 微信分账进程已存在'); return; } \Yii::$app->cache->set($cacheKey, 1, 160); $order_id_arr = []; foreach($receivers_share as $receivers_share1){ sleep(1); //检测微信是否收货 //20240816这里应该是不需要了 直接用下面的WechatMini::getWechatConfig获取配置信息 // Wechat::init($order->store_id); $app = WechatMini::getWechatConfig($order->store_id); if (!$app) { array_push($order_id_arr, $order->id); continue; } $form = new \app\modules\admin\models\WechatThirdForm(['store_id' => $order->store_id]); $order_ = Order::find()->where(['id' => $order->id])->asArray()->one(); $orderNoHead = substr($receivers_share1['order_no'], 0, 2); $model = Order::find(); $where = []; switch ($orderNoHead) { case 'ML': case 'AL': //商盟会员购物订单 $model = Order::find(); $where = [ 'order_no' => $receivers_share1['order_no'], 'is_delete' => 0, 'trade_status' => Order::ORDER_FLOW_CONFIRM ]; break; case 'SC': //当面付订单 $model = \app\plugins\scanCodePay\models\Order::find(); $where = [ 'order_no' => $receivers_share1['order_no'], 'is_delete' => 0, 'is_pay' => 1 ]; break; } $order_ = $model->where($where)->asArray()->one(); $is_trade_managed = $form->is_trade_managed($app); if ($is_trade_managed) { $res = $form->wxOrderStateIsConfirm($app, $order_); if(!$res){ array_push($order_id_arr, $order->id); continue; } } if (!empty($order_id_arr)) { return $order_id_arr; } $open_add_user_price = false; if (intval($receivers_share1['type']) !== SharingReceiver::RECEIVE_MERCHANT_ID) { $open_add_user_price = true; } else { if ($receivers_share1['user_id']) { $open_add_user_price = true; } } if ($open_add_user_price) { if (in_array($receivers_share1['from'], [ SharingReceiver::FROM_BD_AGENT, SharingReceiver::FROM_AREA_AGENT_PROVIDER, SharingReceiver::FROM_AREA_AGENT_CITY, SharingReceiver::FROM_AREA_AGENT_DISTRICT, ])) { $type_agent = StoreShareMoney::TYPE_AREA_AGENT; if (intval($receivers_share1['from']) === SharingReceiver::FROM_BD_AGENT) { $type_agent = StoreShareMoney::TYPE_BD_AGENT; } $result = StoreShareMoney::saveShareMoney( $receivers_share1['saas_id'], $receivers_share1['store_id'], $receivers_share1['rate'], $order->pay_price, $order->id, StoreShareMoney::STATUS_STORE_ORDER, $type_agent, $receivers_share1['amount'], 0, "订单{$order->order_no}自动分账到账{$receivers_share1['amount']}元" ); if (!$result) { continue; } } else { $this->saasUserPriceLog($order, [$receivers_share1], false, "订单{$order->order_no}自动分账到账{$receivers_share1['amount']}元"); } } $profitOrderId || $profitOrderId = $order->order_no; $res = WechatShare::share($order->transaction_id, $profitOrderId, [$receivers_share1], false, false, $order->store_id, $order->is_platform, $order); \Yii::error(['wechatProfitSharingwechatProfitSharing11:', $res]); if ($res['code'] > 0) { $faildDes = !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']; $faildDes && $faildDes = addslashes('(失败:' . $faildDes . ')'); $receivers_share_platform = [[ 'type' => SharingReceiver::RECEIVE_MERCHANT_ID, 'account' => Option::get('sp_mch_id', 0, 'saas')['value'], 'amount' => $receivers_share1['amount'], 'name' => Option::get('sp_name', 0, 'saas')['value'], ]]; //分到平台 if($receivers_share1['type'] == 2){ SharingReceiver::updateAll([ 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,失败金额转到支付商户")'), 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] . "-失败金额转到支付商户" : $res['msg'] . "-失败金额转到支付商户", 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] . "-失败金额转到支付商户" : $res['msg'] . "-失败金额转到支付商户"], ['id' => $receivers_share1['id']]); continue; } sleep(1); $res = WechatShare::share($order->transaction_id, $profitOrderId, $receivers_share_platform, false, false, $order->store_id, $order->is_platform, $order); \Yii::error(['分到平台wechatProfitSharingwechatProfitSharing11:', $res]); if ($res['code'] > 0) { SharingReceiver::updateAll([ 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'), 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] : $res['msg'], 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']], ['id' => $receivers_share1['id']]); // $this->saasUserPriceLog($order, [$receivers_share1], true, '-分账失败'); }else{ SharingReceiver::updateAll([ 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'), 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]); $profitOrderId = $res['res']['order_id']; } } else { $order_id = $res['res']['order_id']; SharingReceiver::updateAll(['updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]); // $this->saasUserPriceLog($order, [$receivers_share1]); if (in_array($receivers_share1['from'], [ SharingReceiver::FROM_BD_AGENT, SharingReceiver::FROM_AREA_AGENT_PROVIDER, SharingReceiver::FROM_AREA_AGENT_CITY, SharingReceiver::FROM_AREA_AGENT_DISTRICT, ])) { $type_agent = StoreShareMoney::TYPE_AREA_AGENT; if (intval($receivers_share1['from']) === SharingReceiver::FROM_BD_AGENT) { $type_agent = StoreShareMoney::TYPE_BD_AGENT; } $result = StoreShareMoney::saveShareMoney( $receivers_share1['saas_id'], $receivers_share1['store_id'], $receivers_share1['rate'], $order->pay_price, $order->id, StoreShareMoney::STATUS_STORE_PAYOUTS, $type_agent, $receivers_share1['amount'], 0, "订单{$order->order_no}自动分账到账{$receivers_share1['amount']}元" ); if (!$result) { continue; } } else { $this->saasUserPriceLog($order, [$receivers_share1], true, date('Y年m月d日 H:i:s'). ",订单{$order->order_no}自动分账到账"); } $profitOrderId = $res['res']['order_id']; } } // 单次分账结束后,剩余金额自动解冻返给商户, 无需主动触发分账完结接口,多次分账时需要最终触发分账完结,最终解冻给商户 // 分账完结 $res = WechatShare::complete($order->transaction_id, $order_id, false, '分账完结', $order->store_id, $order->is_platform ); // return $order_id_arr; \Yii::error(['<=======================> 订单号:' . $order->order_no . '-分账完结结果:', $res]); } public function b2bProfitSharing($order) { \Yii::error('<=======================>订单号:' . $order->order_no . ' b2b分账进程开始'); $receivers_share = SharingReceiver::find()->where(['store_id' => $order->store_id, 'order_no' => $order->order_no, 'is_pay' => SharingReceiver::PAY_WAIT]) ->asArray()->all(); $cacheKey = 'b2bProfitSharing11:' . $order->order_no; if(\Yii::$app->cache->get($cacheKey)){ \Yii::error('<=======================> b2b分账进程已存在'); return; } \Yii::$app->cache->set($cacheKey, 1, 160); $saasRec = []; foreach($receivers_share as $receivers_share1){ sleep(1); if (in_array($receivers_share1['from'], [ SharingReceiver::FROM_BD_AGENT, SharingReceiver::FROM_AREA_AGENT_PROVIDER, SharingReceiver::FROM_AREA_AGENT_CITY, SharingReceiver::FROM_AREA_AGENT_DISTRICT, ])) { $type_agent = StoreShareMoney::TYPE_AREA_AGENT; if (intval($receivers_share1['from']) === SharingReceiver::FROM_BD_AGENT) { $type_agent = StoreShareMoney::TYPE_BD_AGENT; } $result = StoreShareMoney::saveShareMoney( $receivers_share1['saas_id'], $receivers_share1['store_id'], $receivers_share1['rate'], $order->pay_price, $order->id, StoreShareMoney::STATUS_STORE_ORDER, $type_agent, $receivers_share1['amount'], 0, "b2b订单{$order->order_no}自动分账到账{$receivers_share1['amount']}元" ); if (!$result) { continue; } } else { $this->saasUserPriceLog($order, [$receivers_share1], false, "b2b订单{$order->order_no}自动分账到账{$receivers_share1['amount']}钱"); } $isSaas = B2bPay::sharingaccountIsSaas($receivers_share1['account']); if($isSaas){ $saasRec[] = $receivers_share1; continue; } $res = B2bPay::share($order, $receivers_share1); \Yii::error(['wechatProfitSharingwechatProfitSharing11:', $res]); if ($res['code'] > 0) { $saasRec[] = $receivers_share1; $faildDes = $res['code'] ? $res['msg'] : ''; $faildDes && $faildDes = addslashes('(失败:' . $faildDes . ')'); SharingReceiver::updateAll([ 'description' => new Expression('CONCAT(description, "' . $faildDes . '-b2b分账失败,转到服务商")'), 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS], ['id' => $receivers_share1['id']]); } else { SharingReceiver::updateAll(['updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS], ['id' => $receivers_share1['id']]); // $this->saasUserPriceLog($order, [$receivers_share1]); if (in_array($receivers_share1['from'], [ SharingReceiver::FROM_BD_AGENT, SharingReceiver::FROM_AREA_AGENT_PROVIDER, SharingReceiver::FROM_AREA_AGENT_CITY, SharingReceiver::FROM_AREA_AGENT_DISTRICT, ])) { $type_agent = StoreShareMoney::TYPE_AREA_AGENT; if (intval($receivers_share1['from']) === SharingReceiver::FROM_BD_AGENT) { $type_agent = StoreShareMoney::TYPE_BD_AGENT; } $result = StoreShareMoney::saveShareMoney( $receivers_share1['saas_id'], $receivers_share1['store_id'], $receivers_share1['rate'], $order->pay_price, $order->id, StoreShareMoney::STATUS_STORE_PAYOUTS, $type_agent, $receivers_share1['amount'], 0, "b2b订单{$order->order_no}自动分账到账{$receivers_share1['amount']}元" ); if (!$result) { continue; } } else { $this->saasUserPriceLog($order, [$receivers_share1], true, date('Y年m月d日 H:i:s'). ",b2b订单{$order->order_no}自动分账到账"); } } } // 分账完结后,剩余金额自动解冻返给商户 if($saasRec){ $amount = 0; foreach($saasRec as $rec){ $amount += $rec['amount']; } $sharingaccountSaas = B2bPay::sharingaccountSaas(); $receivers_share_platform = [ 'amount' => $amount, 'type' => SharingReceiver::RECEIVE_MERCHANT_ID, 'account' => $sharingaccountSaas['payee_id'], 'name' => $sharingaccountSaas['payee_name'], ]; //分到平台 sleep(1); $res = B2bPay::share($order, $receivers_share_platform); \Yii::error(['b2b分到平台wechatProfitSharingwechatProfitSharing11:', $res]); if ($res['code'] > 0) { $faildDes = $res['code'] ? $res['msg'] : ''; $faildDes && $faildDes = addslashes('(失败:' . $faildDes . ')'); SharingReceiver::updateAll([ 'description' => new Expression('CONCAT(description, "' . $faildDes . '-b2b分账到服务商失败")'), 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => $res['code'], 'err_code_des' => $res['msg']], ['id' => array_column($saasRec, 'id')]); // $this->saasUserPriceLog($order, [$receivers_share1], true, '-分账失败'); } } // 分账完结 $res = B2bPay::shareFinish($order); // return $order_id_arr; \Yii::error(['<=======================> 订单号:' . $order->order_no . '-b2b分账完结结果:', $res]); } public function adapayProfitSharing($order) { $order_id = $order->order_no; $receivers_share = SharingReceiver::find()->where(['store_id' => $order->store_id, 'order_no' => $order->order_no, 'is_pay' => SharingReceiver::PAY_WAIT]) ->asArray()->all(); $profitOrderId = 0; $cacheKey = 'adapayProfitSharing11:' . $order->adapay_payment_id; if(\Yii::$app->cache->get($cacheKey)){ \Yii::error('<=======================> adapay分账进程已存在'); return; } \Yii::$app->cache->set($cacheKey, 1, 160); foreach($receivers_share as $receivers_share1){ sleep(1); if (in_array($receivers_share1['from'], [ SharingReceiver::FROM_BD_AGENT, SharingReceiver::FROM_AREA_AGENT_PROVIDER, SharingReceiver::FROM_AREA_AGENT_CITY, SharingReceiver::FROM_AREA_AGENT_DISTRICT, ])) { $type_agent = StoreShareMoney::TYPE_AREA_AGENT; if (intval($receivers_share1['from']) === SharingReceiver::FROM_BD_AGENT) { $type_agent = StoreShareMoney::TYPE_BD_AGENT; } $result = StoreShareMoney::saveShareMoney( $receivers_share1['saas_id'], $receivers_share1['store_id'], $receivers_share1['rate'], $order->pay_price, $order->id, StoreShareMoney::STATUS_STORE_ORDER, $type_agent, $receivers_share1['amount'], 0, "订单{$order->order_no}自动分账到账{$receivers_share1['amount']}元" ); if (!$result) { continue; } } else { $this->saasUserPriceLog($order, [$receivers_share1], false, "订单{$order->order_no}自动分账到账{$receivers_share1['amount']}钱"); } $res = Adapay::share($order, $receivers_share1); \Yii::error(['adapayProfitSharingadapayProfitSharing11:', $res]); if ($res['code'] > 0) { $faildDes = $res['msg']; $faildDes && $faildDes = addslashes('(失败:' . $faildDes . ')'); //分到平台 if($receivers_share1['type'] == 2){ SharingReceiver::updateAll([ 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] : $res['msg'], 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']], ['id' => $receivers_share1['id']]); continue; } sleep(1); $res = Adapay::shareToSaas($order, $receivers_share1); \Yii::error(['分到平台adapayProfitSharingadapayProfitSharing11:', $res]); if ($res['code'] > 0) { SharingReceiver::updateAll([ 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'), 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] : $res['msg'], 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']], ['id' => $receivers_share1['id']]); // $this->saasUserPriceLog($order, [$receivers_share1]); // $this->saasUserPriceLog($order, [$receivers_share1], true, '-分账失败'); }else{ SharingReceiver::updateAll([ 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'), 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]); } } else { $order_id = $res['res']['order_id']; SharingReceiver::updateAll(['updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]); // $this->saasUserPriceLog($order, [$receivers_share1]); if (in_array($receivers_share1['from'], [ SharingReceiver::FROM_BD_AGENT, SharingReceiver::FROM_AREA_AGENT_PROVIDER, SharingReceiver::FROM_AREA_AGENT_CITY, SharingReceiver::FROM_AREA_AGENT_DISTRICT, ])) { $type_agent = StoreShareMoney::TYPE_AREA_AGENT; if (intval($receivers_share1['from']) === SharingReceiver::FROM_BD_AGENT) { $type_agent = StoreShareMoney::TYPE_BD_AGENT; } $result = StoreShareMoney::saveShareMoney( $receivers_share1['saas_id'], $receivers_share1['store_id'], $receivers_share1['rate'], $order->pay_price, $order->id, StoreShareMoney::STATUS_STORE_PAYOUTS, $type_agent, $receivers_share1['amount'], 0, "订单{$order->order_no}自动分账到账{$receivers_share1['amount']}元" ); if (!$result) { continue; } } else { $this->saasUserPriceLog($order, [$receivers_share1], true, date('Y年m月d日 H:i:s'). ",订单{$order->order_no}自动分账到账"); } } } try{ $shareToSelf = Adapay::shareToSelf($order); if($shareToSelf['code'] == 0){ $order->adapay_share_finish = 1; $order->save(); } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } // 分账完结 \Yii::error(['<=======================> 订单号:' . $order->order_no . '-分账完结结果:']); } /** * 通联分账 * @param $order * @return void */ public function yunstProfitSharing($order) { $order_id = $order->order_no; /** * 查询待分账的记录 */ $receivers_share = SharingReceiver::find()->where(['store_id' => $order->store_id, 'order_no' => $order->order_no]) // ->andWhere(['in','is_pay',[SharingReceiver::PAY_WAIT,SharingReceiver::PAY_FAIL]]) ->andWhere(['is_pay'=>SharingReceiver::PAY_WAIT]) ->asArray()->all(); $profitOrderId = 0; // $cacheKey = 'yunstProfitSharing:' . $order->adapay_payment_id; // if(\Yii::$app->cache->get($cacheKey)){ // \Yii::error('<=======================> yunst分账进程已存在'); // return; // } // // \Yii::$app->cache->set($cacheKey, 1, 160); foreach($receivers_share as $receivers_share1){ sleep(1); //开始分账 //这里重新方法调用orderYunst来实现分账 $res = OrderYunst::share($order, $receivers_share1); debug_log(['<=======================> 订单号:' . $order->order_no . '-分账开始:' . json_encode($res, JSON_UNESCAPED_UNICODE)], 'yunst.log'); //通联分账 if ($res['code'] > 0) { $failedDes = $res['msg']; $failedDes && $failedDes = addslashes('(失败:' . $failedDes . ')'); //分到平台 if($receivers_share1['type'] == 2){ SharingReceiver::updateAll([ 'updated_at' => time(), 'yunst_order_no'=>$res['res']['yunst_order_no'], 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] : $res['msg'], 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']], ['id' => $receivers_share1['id']]); $id = \Yii::$app->cache->get('yunst_receiver_fail_id' . $receivers_share1['id']); if ($id && !\Yii::$app->queue->isDone($id)) { \Yii::$app->queue->remove($id); } $id = \queue_push(new \app\jobs\YunstSharingReceiverHandleFailJob(['order_no' => $order->order_no]), 3600); \Yii::$app->cache->set('yunst_receiver_fail_id' . $receivers_share1['id'], $id); continue; } sleep(1); //如果分账到账户失败再重试 $res = OrderYunst::shareToSaas($order, $receivers_share1); if ($res['code'] > 0) { SharingReceiver::updateAll([ 'description' => new Expression('CONCAT(description, "' . $failedDes . '-分账失败,转到服务商")'), 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] : $res['msg'], 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']], ['id' => $receivers_share1['id']]); // $this->saasUserPriceLog($order, [$receivers_share1]); // $this->saasUserPriceLog($order, [$receivers_share1], true, '-分账失败'); $id = \Yii::$app->cache->get('yunst_receiver_fail_id' . $receivers_share1['id']); if ($id && !\Yii::$app->queue->isDone($id)) { \Yii::$app->queue->remove($id); } $id = \queue_push(new \app\jobs\YunstSharingReceiverHandleFailJob(['order_no' => $order->order_no]), 3600); \Yii::$app->cache->set('yunst_receiver_fail_id' . $receivers_share1['id'], $id); }else{ SharingReceiver::updateAll([ 'description' => new Expression('CONCAT(description, "' . $failedDes . '-分账失败,转到服务商")'), 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]); // $this->saasUserPriceLog($order, [$receivers_share1]); //如果是分账成功自动提现 $this->autoCash($order_id); } } else { $order_id = $res['res']['order_id']; SharingReceiver::updateAll(['updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]); // $this->saasUserPriceLog($order, [$receivers_share1]); // $this->saasUserPriceLog($order, [$receivers_share1], true); //如果是分账成功自动提现 $this->autoCash($order_id); } } // 分账完结 debug_log(['<=======================> 订单号:' . $order->order_no . '-分账完结结果:'], 'yunst.log'); } /** * 自动提现 * @return void */ public function autoCash($order_id) { $sharing_info = SharingReceiver::find()->where(['order_id' => $order_id, 'is_pay' => SharingReceiver::PAY_SUCCESS])->one(); if ($sharing_info){ $order_info = \app\plugins\scanCodePay\models\Order::find()->where(['id' => $sharing_info->order_id])->one(); if ($order_info){ $store_price = $sharing_info->amount; $mch_price = ($order_info->pay_price - $sharing_info->amount); //平台提现 $cash = new StoreCash(); $cash->order_no = \app\utils\OrderNo::getOrderNo(\app\utils\OrderNo::ORDER_CASH); $cash->is_delete = 0; $cash->status = 0; $cash->price = $store_price; $cash->created_at = time(); $cash->store_id = -1; $cash->type =6;//通联提现 $cash->name = '平台提现'; $cash->mobile = ''; $cash->pay_time = 0; $cash->service_charge = 0; $cash->cash_type = 0; if ($cash->save()) { $oldConf = Option::get(OptionSetting::SAAS_YUNST_SETTING, 0, 'saas')['value']; if ($oldConf) { $oldConf = json_decode($oldConf, true); if (!empty($oldConf)) { $customer_number = $oldConf['customer_number']; //调用通联自动提现接口 $orderYunst = new OrderYunst(); $res = $orderYunst->queryAcctInfo($customer_number); debug_log($res); $amount = 0; if ($res['subCode'] == 'SUCCESS'){ $amount = $res['data']['amount'];//真的 } if ($store_price > $amount) { debug_log('平台提现金额大于通联账户余额'); } $orderYunst = new OrderYunst(); $data['bizOrderNo'] = $cash->order_no; $data['bizUserId'] = $customer_number;//代理商号 $data['amount'] = intval($cash->price * 100); $data['notifyUrl'] = \Yii::$app->request->hostInfo; $data['remark'] = ""; $data['authWay'] = "3"; $res_cash = $orderYunst->servicerWithdraw($data); debug_log($res_cash); if ($res_cash['subCode'] != 'SUCCESS'){ debug_log('平台提现失败'); debug_log($res_cash['subMsg']); $cash_info2 = StoreCash::findOne($cash->id); $order_no = \app\utils\OrderNo::getOrderNo(\app\utils\OrderNo::ORDER_CASH); $cash_info2->order_no = $order_no; $cash_info2->save(); }else{ $cash_info = StoreCash::findOne($cash->id); $cash_info->status = 2; $cash_info->pay_time = time(); $cash_info->save(); debug_log('平台提现成功'); } } } } //商户提现 $cash_mch = new StoreCash(); $cash_mch->order_no = \app\utils\OrderNo::getOrderNo(\app\utils\OrderNo::ORDER_CASH); $cash_mch->is_delete = 0; $cash_mch->status = 0; $cash_mch->price = $mch_price; $cash_mch->created_at = time(); $cash_mch->store_id = $sharing_info->store_id; $cash_mch->type =6;//通联提现 $cash_mch->name = '商户提现'; $cash_mch->mobile = ''; $cash_mch->pay_time = 0; $cash_mch->service_charge = 0; $cash_mch->cash_type = 0; if ($cash_mch->save()) { //调用通联自动提现接口 $store = \app\models\Store::findOne($sharing_info->store_id); $orderYunst = new OrderYunst(); $res2 = $orderYunst->queryAcctInfo($store->store_number); debug_log($res2); $amount2 = 0; if ($res2['subCode'] == 'SUCCESS'){ $amount2 = $res2['data']['amount'];//真的 } if ($mch_price > $amount2) { debug_log('平台提现金额大于通联账户余额'); } $orderYunst = new OrderYunst(); $data['bizOrderNo'] = $cash_mch->order_no; $store = Store::findOne(['id' => $cash_mch->store_id]); $data['bizUserId'] = $store->store_number; $data['amount'] = intval($cash_mch->price * 100); $data['notifyUrl'] = \Yii::$app->request->hostInfo; $data['remark'] = ""; $data['authWay'] = "3"; $res_cash2 = $orderYunst->servicerWithdraw($data); debug_log($res_cash2); if ($res_cash2['subCode'] != 'SUCCESS'){ debug_log('商户提现失败'); debug_log($res_cash2['subMsg']); $cash_info2 = StoreCash::findOne($cash_mch->id); $order_no = \app\utils\OrderNo::getOrderNo(\app\utils\OrderNo::ORDER_CASH); $cash_info2->order_no = $order_no; $cash_info2->save(); }else{ $cash_info2 = StoreCash::findOne($cash_mch->id); $cash_info2->status = 2; $cash_info2->pay_time = time(); $cash_info2->save(); debug_log('商户提现成功'); } } }else{ debug_log('订单不存在,提现失败'); } }else{ debug_log('分账不存在,提现失败'); } } /** * 支付宝分账 * @param Order | \app\plugins\scanCodePay\models\Order | ReOrder | FoodOrder $order * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException * @throws \GuzzleHttp\Exception\GuzzleException */ public function alipayProfitSharing($order, &$order_id_arr = []) { if (!$order) { \Yii::error('<=======================> 支付宝分账订单不存在'); return; } $receivers_share = SharingReceiver::find()->where(['store_id' => $order->store_id, 'is_pay' => SharingReceiver::PAY_WAIT, 'order_no' => $order->order_no, 'execute_type' => SharingReceiver::EXECUTE_TYPE_ALIPAY]) ->asArray()->all(); debug_log(['receivers_share' => $receivers_share], 'profitSharing.log'); if (empty($receivers_share)) { \Yii::error('<=======================> 订单号:' . $order->order_no . '分账接收人为空'); return; } $cacheKey = 'alipayProfitSharing11:' . $order->order_no; // if(\Yii::$app->cache->get($cacheKey)){ // \Yii::error('<=======================> 支付宝分账进程已存在'); // return; // } \Yii::$app->cache->set($cacheKey, 1, 160); foreach ($receivers_share as $receiver) { sleep(1); $res_arr = []; $trans_in_type = 'loginName'; if (strpos($receiver['account'], '2088') !== false) { $trans_in_type = 'userId'; } $res_arr[] = [ 'royalty_type' => 'transfer', 'trans_in_type' => $trans_in_type, 'amount' => $receiver['amount'], 'trans_in' => $receiver['account'], 'desc' => $receiver['description'] ]; $storeInfo = Store::find()->where(['id'=>$order->store_id,'is_delete'=>0])->asArray()->one(); // if ($storeInfo['business_model'] != 1) { // $res = AlipayUnion::settle($order->order_no, $order->alipay_trade_no, $res_arr, $order->store_id,'true'); // } else { $is_app = false; if ($order->order_origin === Order::ORDER_SOURCE_APP) { $is_app = true; } debug_log(['order_no' => $order->order_no, 'alipay_trade_no' => $order->alipay_trade_no, 'res_arr' => $res_arr, 'store_id' => $order->store_id], 'profitSharing.log'); $res = AlipayProfit::settle($order->order_no, $order->alipay_trade_no, $res_arr, $order->store_id,'true', $is_app); // } if (in_array($receiver['from'], [ SharingReceiver::FROM_BD_AGENT, SharingReceiver::FROM_AREA_AGENT_PROVIDER, SharingReceiver::FROM_AREA_AGENT_CITY, SharingReceiver::FROM_AREA_AGENT_DISTRICT, ])) { $type_agent = StoreShareMoney::TYPE_AREA_AGENT; if (intval($receiver['from']) === SharingReceiver::FROM_BD_AGENT) { $type_agent = StoreShareMoney::TYPE_BD_AGENT; } $result = StoreShareMoney::saveShareMoney( $receiver['saas_id'], $receiver['store_id'], $receiver['rate'], $order->pay_price, $order->id, StoreShareMoney::STATUS_STORE_ORDER, $type_agent, $receiver['amount'], 0, "订单{$order->order_no}自动分账到账{$receiver['amount']}元" ); if (!$result) { continue; } } else { $this->saasUserPriceLog($order, [$receiver], false, "订单{$order->order_no}自动分账到账{$receiver['amount']}元"); } \Yii::error(['<=======================> 订单号:' . $order->order_no . ', 分销请求分账结果:', $res]); if ($res['code'] > 0) { if (isset($res['res']['sub_code']) && $res['res']['sub_code'] === 'ACQ.TXN_RESULT_ACCOUNT_BALANCE_NOT_ENOUGH') { //账户余额不足 array_push($order_id_arr, $order->id); break; } $faildDes = $res['res']['sub_msg']; $faildDes && $faildDes = addslashes('(失败:' . $faildDes . ')'); $receivers_share_platform = []; $amount = $receiver['amount']; $receivers_share_platform[] = [ 'royalty_type' => 'transfer', 'trans_in_type' => 'userId', 'amount' => $amount, 'trans_in' => Option::get('alipay_user_id', 0, 'saas')['value'], 'desc' => '分账到平台', ]; //分到平台 if($receiver['type'] == 2){ SharingReceiver::updateAll([ 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => $res['res']['code'], 'err_code_des' => $res['res']['sub_msg']], ['id' => $receiver['id']]); continue; } sleep(1); // if ($storeInfo['business_model'] != 1) { // $res = AlipayUnion::settle($order->order_no, $order->alipay_trade_no, $receivers_share_platform, $order->store_id,'true'); // } else { $is_app = false; if ($order->order_origin === Order::ORDER_SOURCE_APP) { $is_app = true; } $res = AlipayProfit::settle($order->order_no, $order->alipay_trade_no, $receivers_share_platform, $order->store_id,'true', $is_app); // } \Yii::error(['分到平台wechatProfitSharingwechatProfitSharing11:', $res]); if ($res['code'] > 0) { SharingReceiver::updateAll([ 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'), 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => $res['res']['code'], 'err_code_des' => $res['res']['sub_msg']], ['id' => $receiver['id']]); // $this->saasUserPriceLog($order, [$receiver]); // $this->saasUserPriceLog($order, [$receiver], true, '-分账失败'); }else{ SharingReceiver::updateAll([ 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'), 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS], ['id' => $receiver['id']]); } return; } SharingReceiver::updateAll(['updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS], ['id' => $receiver['id']]); // $this->saasUserPriceLog($order, $receivers_share); if (in_array($receiver['from'], [ SharingReceiver::FROM_BD_AGENT, SharingReceiver::FROM_AREA_AGENT_PROVIDER, SharingReceiver::FROM_AREA_AGENT_CITY, SharingReceiver::FROM_AREA_AGENT_DISTRICT, ])) { $type_agent = StoreShareMoney::TYPE_AREA_AGENT; if (intval($receiver['from']) === SharingReceiver::FROM_BD_AGENT) { $type_agent = StoreShareMoney::TYPE_BD_AGENT; } $result = StoreShareMoney::saveShareMoney( $receiver['saas_id'], $receiver['store_id'], $receiver['rate'], $order->pay_price, $order->id, StoreShareMoney::STATUS_STORE_PAYOUTS, $type_agent, $receiver['amount'], 0, "订单{$order->order_no}自动分账到账{$receiver['amount']}元" ); if (!$result) { continue; } } else { $this->saasUserPriceLog($order, $receivers_share, true, date('Y年m月d日 H:i:s'). ",订单{$order->order_no}自动分账到账"); } } } public function saasUserPriceLog($order, $SharingReceivers = [], $expend = false, $log = '') { try { $log_type = SaasUserPriceLog::LOG_TYPE_INCOME; $remark = ''; if($expend){ $log_type = SaasUserPriceLog::LOG_TYPE_EXPEND; $remark = '-分账成功'; } $log && $remark = $log; foreach ($SharingReceivers as $item) { \Yii::warning(['---- saasUserPriceLog Err11 ----', $item]); if(intval($item['type']) === SharingReceiver::RECEIVE_MERCHANT_ID && !intval($item['user_id'])){ continue; } $desc = $item['remark'] . $remark; $saas_id = $item['saas_id']; if(!$saas_id){ if(!$order->is_platform){ $saas_id = $item['user_id']; }else{ $userInfo = User::findOne($item['user_id']); if(!empty($userInfo)){ $saas = SaasUser::findOne(['mobile' => $userInfo->binding]); $saas_id = $saas->id; } } } \Yii::warning(['---- saasUserPriceLog Err22 ----', $saas_id, $item['amount'], $item['from'], $log_type, $order->order_no, $desc]); SaasUserPriceLog::saveLog($saas_id, $item['amount'], $item['from'], $log_type, $order->order_no, $desc); } } catch (\Exception $e) { \Yii::warning('---- saasUserPriceLog Err ----' . __LINE__); } } // 分享员佣金结算 public function video_shop_order_share_money($id) { $order_id = $id; \Yii::warning(['分享员佣金结算:0000', $order_id]); $VideoShopOrderExt = VideoShopOrderExt::findOne(['order_id' => $order_id]); if (!$VideoShopOrderExt) { return; } $order = Order::findOne($order_id); if (!$order) { return; } if ($VideoShopOrderExt->is_price != 0) { return; } $VideoShopOrderExt->is_price = 1; $VideoShopOrderExt->save(); $user_1 = User::findOne($VideoShopOrderExt->old_parent_id); if (!$user_1) { return; } $user_1->updateCounters(['total_price' => $VideoShopOrderExt->first_price, 'price' => $VideoShopOrderExt->first_price]); UserShareMoney::set($VideoShopOrderExt->first_price, $user_1->id, $order_id, 0, 1, $VideoShopOrderExt->store_id, 0, '分享员获得佣金, 订单号:' . $order->order_no); \Yii::warning(['分享员佣金结算:1', $VideoShopOrderExt->store_id, $order_id, $user_1->id, $VideoShopOrderExt->first_price]); $order->updateCounters(['share_price' => doubleval($VideoShopOrderExt->first_price)]); return; } // 分销订单佣金结算 public function share_money($id) { $order_id = $id; if(isset($order_id->id)){ $order = $order_id; }else{ $order = Order::findOne($order_id); } if (!$order) { return; } if ($order->is_price != 0) { return; } //排除商盟订单 if($order->user_id == 0) { return; } $setting = Option::get('share_money_setting', $order->store_id); $setting = $setting ? Json::decode($setting['value']) : []; if (!$setting) { \Yii::warning('订单佣金发送:未开启分销设置1'); return; } // if (!is_array($setting['commission_type']) || empty($setting['commission_type'])) { // \Yii::warning('订单佣金发送:未开启分销设置2'); // return; // } // $commission_type = $setting['commission_type']; // // 订单佣金 2 // if (in_array(2, $commission_type)) { // $this->sendOrderProfit($order, $setting['expire_day']); //临时关系佣金发放 try { if (!empty($order->limit_id) && !empty($order->limit_price)) { \Yii::error("临时绑定关系发放佣金", '临时绑定关系发放佣金'); //临时绑定关系发放佣金 $bind_log = UserBindLog::findOne($order->limit_id); $user = User::findOne($bind_log->parent_id); $user->updateCounters(['total_price' => $order->limit_price, 'price' => $order->limit_price]); UserShareMoney::set($order->limit_price, $user->id, $order->id, 0, 6, $order->store_id, 0); $order->is_send_limit = 1; $order->updateCounters(['share_price' => doubleval($order->limit_price)]); $res = $order->save(); if (!$res) { \Yii::error("订单保存失败"); }; } else { \Yii::error("订单中临时关系佣金为空"); } } catch (\Throwable $e) { \Yii::error("订单中临时关系佣金发放失败: " . $e->getMessage()); } // } else { // \Yii::warning('订单佣金发送:未开启订单佣金分销'); // } // // 会员佣金 // if (!in_array(1, $commission_type)) { // \Yii::warning('订单佣金发送:未开启会员佣金分销'); // return; // } $share_setting = Option::get('share_basic_setting', $order->store_id); $share_setting = $share_setting ? Json::decode($share_setting['value']) : []; // 分销商自购返利 $order->share_price = 0; $user = User::findOne(['id' => $order->user_id]); if ($order->rebate > 0) { if ($order->share_send_type == 2) { AccountLog::saveLog($order->user_id, $order->rebate, AccountLog::TYPE_INTEGRAL, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "商城订单自购返利赠送积分, 订单号:{$order->order_no}"); } else if ($order->share_send_type == 3) { AccountLog::saveLog($order->user_id, $order->rebate, AccountLog::TYPE_BALANCE, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "商城订单自购返利赠送余额, 订单号:{$order->order_no}"); } else { $user->updateCounters(['total_price' => doubleval($order->rebate), 'price' => doubleval($order->rebate)]); $order->updateCounters(['share_price' => doubleval($order->rebate)]); UserShareMoney::set($order->rebate, $user->id, $order->id, 0, 4, $order->store_id, 0); } } // 一级佣金发放 if ($share_setting['level']['value'] >= 1) { $user_1 = User::findOne($order->old_parent_id); if (!$user_1) { $order->save(); return; } if ($order->share_send_type == 2 && $order->first_price > 0) { AccountLog::saveLog($user_1->id, $order->first_price, AccountLog::TYPE_INTEGRAL, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "商城订单分销赠送积分, 订单号:{$order->order_no}"); } else if ($order->share_send_type == 3 && $order->first_price > 0) { AccountLog::saveLog($user_1->id, $order->first_price, AccountLog::TYPE_BALANCE, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "商城订单分销赠送余额, 订单号:{$order->order_no}"); } else { $user_1->updateCounters(['total_price' => $order->first_price, 'price' => $order->first_price]); UserShareMoney::set($order->first_price, $user_1->id, $order->id, 0, 1, $order->store_id, 0); $order->updateCounters(['share_price' => doubleval($order->first_price)]); } } // 二级佣金发放 if ($share_setting['level']['value'] >= 2) { $user_2 = User::findOne($order->old_parent_id_1); if ($user_2) { if ($order->share_send_type == 2 && $order->second_price > 0) { AccountLog::saveLog($user_2->id, $order->second_price, AccountLog::TYPE_INTEGRAL, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "商城订单分销赠送积分, 订单号:{$order->order_no}"); } else if ($order->share_send_type == 3 && $order->second_price > 0) { AccountLog::saveLog($user_2->id, $order->second_price, AccountLog::TYPE_BALANCE, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "商城订单分销赠送余额, 订单号:{$order->order_no}"); } else { $user_2->updateCounters(['total_price' => $order->second_price, 'price' => $order->second_price]); UserShareMoney::set($order->second_price, $user_2->id, $order->id, 0, 2, $order->store_id, 0); $order->updateCounters(['share_price' => doubleval($order->second_price)]); } } } // 三级佣金发放 if ($share_setting['level']['value'] >= 3 && $order->rebate == 0) { $user_3 = User::findOne($order->old_parent_id_2); if ($user_3) { if ($order->share_send_type == 2 && $order->third_price > 0) { AccountLog::saveLog($user_3->id, $order->third_price, AccountLog::TYPE_INTEGRAL, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "商城订单分销赠送积分, 订单号:{$order->order_no}"); } else if ($order->share_send_type == 3 && $order->third_price > 0) { AccountLog::saveLog($user_3->id, $order->third_price, AccountLog::TYPE_BALANCE, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "商城订单分销赠送余额, 订单号({$order->order_no})"); } else { $user_3->updateCounters(['total_price' => $order->third_price, 'price' => $order->third_price]); UserShareMoney::set($order->third_price, $user_3->id, $order->id, 0, 3, $order->store_id, 0); $order->updateCounters(['share_price' => doubleval($order->third_price)]); } } } if ( (!empty($order->limit_id) && !empty($order->limit_price)) || $order->rebate > 0 || $share_setting['level']['value'] >= 1 || $share_setting['level']['value'] >= 2 || ($share_setting['level']['value'] >= 3 && $order->rebate == 0) ) { $order->is_price = 1; } $order->save(); return; } // 股东等级分佣结算 public function share_holder_money($id) { $order_id = $id; if(isset($order_id->id)){ $order = $order_id; }else{ $order = Order::findOne($order_id); } if (!$order) { return; } if ($order->holder_is_price != 0) { return; } //商盟订单没有股东分红 if($order->user_id == 0){ return; } // 一级佣金发放 if ($order->holder_first_price > 0) { $user_1 = User::findOne($order->parent_id); $user_1->updateCounters(['total_price' => $order->holder_first_price, 'price' => $order->holder_first_price]); UserShareMoney::set($order->holder_first_price, $user_1->id, $order->id, 2, 1, $order->store_id, 0); $order->holder_is_price = 1; $order->updateCounters(['share_price' => doubleval($order->holder_first_price)]); } // 二级佣金发放 if ($order->holder_second_price > 0) { $user_2 = User::findOne($order->parent_id_1); $user_2->updateCounters(['total_price' => $order->holder_second_price, 'price' => $order->holder_second_price]); UserShareMoney::set($order->holder_second_price, $user_2->id, $order->id, 2, 2, $order->store_id, 0); $order->updateCounters(['share_price' => doubleval($order->holder_second_price)]); } // 三级佣金发放 if ($order->holder_third_price > 0) { $user_3 = User::findOne($order->parent_id_2); $user_3->updateCounters(['total_price' => $order->holder_third_price, 'price' => $order->holder_third_price]); UserShareMoney::set($order->holder_third_price, $user_3->id, $order->id, 2, 3, $order->store_id, 0); $order->updateCounters(['share_price' => doubleval($order->holder_third_price)]); } // 旧关系发放 // 一级佣金发放 if ($order->old_holder_first_price > 0) { $user_1 = User::findOne($order->old_parent_id); $user_1->updateCounters(['total_price' => $order->old_holder_first_price, 'price' => $order->old_holder_first_price]); UserShareMoney::set($order->old_holder_first_price, $user_1->id, $order->id, 2, 1, $order->store_id, 0); $order->updateCounters(['share_price' => doubleval($order->old_holder_first_price)]); } // 二级佣金发放 if ($order->old_holder_second_price > 0) { $user_2 = User::findOne($order->old_parent_id_1); $user_2->updateCounters(['total_price' => $order->old_holder_second_price, 'price' => $order->old_holder_second_price]); UserShareMoney::set($order->old_holder_second_price, $user_2->id, $order->id, 2, 2, $order->store_id, 0); $order->updateCounters(['share_price' => doubleval($order->old_holder_second_price)]); } // 三级佣金发放 if ($order->old_holder_third_price > 0) { $user_3 = User::findOne($order->old_parent_id_2); $user_3->updateCounters(['total_price' => $order->old_holder_third_price, 'price' => $order->old_holder_third_price]); UserShareMoney::set($order->old_holder_third_price, $user_3->id, $order->id, 2, 3, $order->store_id, 0); $order->updateCounters(['share_price' => doubleval($order->old_holder_third_price)]); } $order->save(); } /** * 积分发放 */ public function give_integral($id) { $order_id = $id; if(isset($order_id->id)){ $give = $order_id; }else{ $give = Order::findOne($order_id); } if ($give['give_integral'] != 0) { return; } $integral = OrderDetail::find() ->andWhere(['order_id' => $give['id'], 'is_delete' => 0]) ->select([ 'sum(integral)', ])->scalar(); if (!$integral) { return; } $giveUser = User::findOne(['id' => $give['user_id']]); AccountLog::saveLog($giveUser->id, $integral, AccountLog::TYPE_INTEGRAL, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $give->id, '订单'.$give->order_no.'赠送积分'); $give->give_integral = 1; $give->save(); } // 团长佣金结算 public function shop_share($id,$type=0) { if ($id) { $shopShare = ShopShare::findOne([ 'order_id' => $id, 'type' => $type ]); if ($shopShare->shop_id && $shopShare->status == 0) { $shop = Shop::findOne($shopShare->shop_id); if ($shop && $shop->user_id) { $form = User::findOne(['id' => $shop->user_id]); $form->updateCounters(['tuan_price' => $shopShare->amount]); $shopShare->status = 1; $shopShare->save(); } } } } public function league_price($id){ $order_id = $id; if(isset($order_id->id)){ $order = $order_id; }else{ $order = Order::findOne($order_id); } $store = Store::findOne($order->store_id); $user = User::findOne($order->user_id); $saas_user = SaasUser::findOne(['mobile' => $user->binding]); if($order->send_price > 0){ // && $store->league_price > 0 //给用户发放联盟券 $send_price = $order->send_price; if($saas_user){ // $store->league_price -= $send_price; // $store->save(); $before = $saas_user->league_price; $saas_user->updateCounters(['league_price' => floatval($send_price)]); SaaSLeaguePriceLog::setLeaguePriceLog( $order->store_id, $saas_user->id, $send_price, $before, SaaSLeaguePriceLog::TYPE_ORDER_REBATE, SaaSLeaguePriceLog::SEND_TYPE, SaaSLeaguePriceLog::ROLE_USER, $order->id ); } $before = $store->league_price; $store->updateCounters(['league_price' => -floatval($send_price)]); SaaSLeaguePriceLog::setLeaguePriceLog( $order->store_id, $saas_user->id, $send_price, $before, SaaSLeaguePriceLog::TYPE_ORDER_REBATE, SaaSLeaguePriceLog::TAKE_TYPE, SaaSLeaguePriceLog::ROLE_STORE, $order->id ); } if($order->take_price > 0){ //给商家增加 (用户抵扣钱从赠送给商家) $before = $store->league_price; //给商家返券 $store->league_price += floatval($order->take_price); $store->save(); $after = $store->league_price; $model = new SaaSLeaguePriceLog(); $model->saas_user_id = $saas_user->id; $model->store_id = $order->store_id; $model->league_price = $order->take_price; $model->type = 2; //下单返利 $model->before = $before; $model->after = $after; $model->order_id = $order->id; $model->addtime = time(); $model->role = SaaSLeaguePriceLog::ROLE_STORE; $model->save(); } } /** * 门店收益计算 */ public function handleMdProfit($order_id) { $md_profit = MdProfit::findOne(['order_id' => $order_id, 'is_send' => 0]); if ($md_profit) { $md = Md::findOne($md_profit->md_id); $md->updateCounters(['total_profit' => $md_profit->total_profit, 'cash_profit' => $md_profit->total_profit]); $md_profit->is_send = 1; $md_profit->save(); } } /** * 抖品发放佣金 */ public function sendVideoGoodsProfit($id) { try { $video_share = VideoGoodsShare::find()->where(['order_id' => $id, 'is_pay' => 1, 'is_send' => 0])->all(); foreach ($video_share as $item) { $item->is_send = 1; $item->send_time = time(); if ($item->save()) { $user = User::findOne($item->author_user_id); $user->total_price = ((float)$user->total_price + (float)$item->proportion); $user->price = ((float)$user->price + (float)$item->proportion); if ($user->save()) { $UserShareMoney = new UserShareMoney(); $UserShareMoney->store_id = $item->store_id; $UserShareMoney->order_id = $item->order_id; $UserShareMoney->user_id = $item->author_user_id; $UserShareMoney->type = 0; $UserShareMoney->source = 1; $UserShareMoney->money = $item->proportion; $UserShareMoney->created_at = time(); $UserShareMoney->order_type = 0; $UserShareMoney->is_delete = 0; $UserShareMoney->version = cyy_version(); $UserShareMoney->save(); } } } } catch (\Exception $e) { \Yii::error($e->getMessage()); } } public function agencyPrice($order_id){ try { if(isset($order_id->id)){ $order = $order_id; }else{ $order = Order::findOne($order_id); } if (in_array($order->pay_type, [Order::PAY_TYPE_WECHAT, Order::PAY_TYPE_ALI])) { throw new \Exception('订单是微信或支付宝支付,不在这里计算发放佣金'); } $order_id = $order->id; $agency_price_config = Option::get('agency_price_config', 0, 'saas')['value']; $agency_price_config = json_decode($agency_price_config, true) ?: []; $province_percent = $agency_price_config['province_percent'] ?? 0; $city_percent = $agency_price_config['city_percent'] ?? 0; $district_percent = $agency_price_config['district_percent'] ?? 0; $bd_agency_price_config = Option::get('bd_agency_price_config', 0, 'saas')['value']; $bd_agency_price_config = json_decode($bd_agency_price_config, true) ?: []; $bd_agent_percent = $bd_agency_price_config['bd_agent_percent'] ?? 0; //获取代理商ID $store = Store::findOne($order->store_id); $admin_list = Admin::find()->where(['province_id' => $store->province_id, 'is_delete' => 0, 'type' => 'admin'])->asArray()->all(); $user = User::findOne($order->user_id); $saasUser = SaasUser::findOne(['mobile' => $user->binding]); $saas_user_name = '-'; if ($saasUser) { $saas_user_name = $saasUser->name; } //推广代理 if($store->salesman_id){ $salesman = Salesman::findOne($store->salesman_id); $bd = Admin::find()->where(['type' => Admin::ADMIN_TYPE_BD_AGENT, 'id' => $salesman['admin_id']])->asArray()->one(); if($bd){ $admin_list[] = $bd; } } foreach ($admin_list as $item) { $ag_rebate = 0; $rate = 0; $desc = ''; $type = StoreShareMoney::TYPE_AREA_AGENT; if($item['type'] == Admin::ADMIN_TYPE_BD_AGENT){ $ag_rebate = $order->ag_rebate * ($bd_agent_percent / 100); $ag_rebate = sprintf("%.2f", $ag_rebate); $rate = $bd_agent_percent; $desc = '用户' . $saas_user_name . '下单,订单' . $order->order_no . ',发放 ' . $ag_rebate . '元推广代佣金'; $type = StoreShareMoney::TYPE_BD_AGENT; } //省 if ((int)$item['area_level'] === 3) { $ag_rebate = $order->ag_rebate * ($province_percent / 100); $ag_rebate = sprintf("%.2f", $ag_rebate); $rate = $province_percent; $desc = '用户' . $saas_user_name . '下单,订单' . $order->order_no . ',发放 ' . $ag_rebate . '元省代佣金'; } //市 if ((int)$item['area_level'] === 2 && (int)$item['city_id'] === (int)$store->city_id) { $ag_rebate = $order->ag_rebate * ($city_percent / 100); $ag_rebate = sprintf("%.2f", $ag_rebate); $rate = $city_percent; $desc = '用户' . $saas_user_name . '下单,订单' . $order->order_no . ',发放 ' . $ag_rebate . '元市代佣金'; } //区 if ((int)$item['area_level'] === 1 && (int)$item['city_id'] === (int)$store->city_id && (int)$item['district_id'] === (int)$store->district_id) { $ag_rebate = $order->ag_rebate * ($district_percent / 100); $ag_rebate = sprintf("%.2f", $ag_rebate); $rate = $district_percent; $desc = '用户' . $saas_user_name . '下单,订单' . $order->order_no . ',发放 ' . $ag_rebate . '元区代佣金'; } if ($ag_rebate <= 0) { continue; } $StoreShareMoney = StoreShareMoney::findOne(['user_id' => $item['saas_user_id'], 'store_id' => $store->id, 'order_id' => $order_id, 'type' => $type]); if($StoreShareMoney){ continue; } //给用户增加佣金 $SaasUser = SaasUser::findOne($item['saas_user_id']); $SaasUser->share_profit = ($SaasUser->share_profit * 1) + ($ag_rebate * 1); $res = $SaasUser->save(); //增加记录 if ($res) { $form = new StoreShareMoney(); $form->user_id = $SaasUser->id; $form->store_id = $store->id; $form->profit = $rate; $form->total_price = $order->total_price; $form->desc = $desc; $form->order_id = $order_id; $form->created_at = time(); $form->type = $type; $form->status = StoreShareMoney::STATUS_STORE_ORDER; $form->commission = $ag_rebate; $form->is_send = 1; $res = $form->save(); if (!$res) { debug_log($form->errors); } } } return [ 'code' => 0, 'msg' => '处理完成' ]; } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage(), ]; } } /** * 推广代理二级佣金 * @param $order_id * @return void */ public function agencyPriceTwo($order_id){ try { if(isset($order_id->id)){ $order = $order_id; }else{ $order = Order::findOne($order_id); } $order_id = $order->id; //获取代理商ID $store = Store::findOne($order->store_id); $user = User::findOne($order->user_id);//下单用户 $saasUser = SaasUser::findOne(['mobile' => $user->binding]);//联盟用户 $saas_user_name = '-'; if ($saasUser) { $saas_user_name = $saasUser->name; } //推广代理 if($store->admin_id){ // $salesman = Salesman::findOne($store->salesman_id);//业务员 $bd = Admin::find()->where(['type' => Admin::ADMIN_TYPE_BD_AGENT, 'id' => $store->admin_id])->asArray()->one(); if($bd){ $admin_list[] = $bd; } } $saas_transfer_profit = $store->transfer_profit; $saas_share_money = round($order->pay_price * $saas_transfer_profit / 100, 2); $defaultSet = Option::get(OptionSetting::SHARE_STORE_DEFAULT_SETTING, -1, OptionSetting::SHARE_GROUP_NAME, '{}'); $defaultSet = json_decode($defaultSet['value'], true); if(!empty($defaultSet['store_share_two_value'])){ $store->store_share_value = $defaultSet['store_share_two_value']; } if(empty($store->store_share_value)){ return; } $saas_store_1_money = floor_num($saas_share_money * ($store->store_share_value / 100), 2); foreach ($admin_list as $item) { $ag_rebate = 0; $rate = 0; $desc = ''; $type = StoreShareMoney::TYPE_BD_AGENT; if($item['type'] == Admin::ADMIN_TYPE_BD_AGENT){ $rate = $store->store_share_value; $desc = '用户' . $saas_user_name . '下单,订单' . $order->order_no . ',发放 ' . $saas_store_1_money . '元推广代佣金'; $type = StoreShareMoney::TYPE_BD_AGENT; } //给用户增加佣金 $SaasUser = SaasUser::findOne($item['saas_user_id']); $SaasUser->share_profit = ($SaasUser->share_profit * 1) + ($saas_store_1_money * 1); $res = $SaasUser->save(); //增加记录 if ($res) { $form = new StoreShareMoney(); $form->user_id = $SaasUser->id; $form->store_id = $store->id; $form->profit = $rate; $form->total_price = $order->total_price; $form->desc = $desc; $form->order_id = $order_id; $form->created_at = time(); $form->type = $type; $form->status = StoreShareMoney::STATUS_STORE_ORDER; $form->commission = $saas_store_1_money; $form->is_send = 1; $res = $form->save(); if (!$res) { debug_log($form->errors); } } } } catch (\Exception $e) { \Yii::error($e->getMessage()); } } public function sendGoodsAgentMoney($order_id){ $t = \Yii::$app->db->beginTransaction(); try { if(isset($order_id->id)){ $order = $order_id; }else{ $order = Order::findOne($order_id); } $order_id = $order->id; $option = Option::get('goods_agent_price_config', 0, 'saas', [])['value']; $option = json_decode($option, true); $goods_agent_percent = $option['goods_agent_percent'] ?? 0; $goods_agent_install_percent = $option['goods_agent_install_percent'] ?? 0; //订单中是否包含产品代理绑定的产品 $order_detail = OrderDetail::find()->alias('od') ->leftJoin(['g' => Goods::tableName()], 'od.goods_id = g.id')->where(['od.order_id' => $order->id]) ->select('od.id, g.cloud_goods_id, od.total_price, g.cloud_supplier_id, g.name, g.is_wholesale')->asArray()->all(); foreach ($order_detail as $value) { //计算产品代理佣金 $supplier_rate = 0; if (!empty($value['cloud_supplier_id'])) { $supplier = Supplier::findOne(['cloud_supplier_id' => $value['cloud_supplier_id']]); $supplier_rate = $supplier->rate; } if (!empty($value['cloud_goods_id']) && !intval($value['is_wholesale'])) { //抓取云仓佣金 $cloud_url = "/goods/getGoodsInfo"; $cloud_data = []; $cloud_data['goods_id'] = $value['cloud_goods_id']; $domain = (new OptionSetting)->getCloudDomainName(); $cloud_info = cloud_post($domain . $cloud_url, $cloud_data); $cloud_info = json_decode($cloud_info, true); if($cloud_info['code'] != 0){ throw new \Exception($cloud_info['msg']); }else{ $goods = $cloud_info['data']['goods']; $agent_profit_default = (int)$goods['agent_profit_default']; if (!$agent_profit_default) { $goods_agent_percent = $goods['agent_percent']; $goods_agent_install_percent = $goods['agent_install_percent']; } } $agent_goods_bind_goods = AgentGoodsBindGoods::find()->where(['cloud_goods_id' => $value['cloud_goods_id'], 'is_delete' => 0, 'status' => 1]) ->select('goods_agent_admin_id, cloud_supplier_id')->asArray()->all(); if (!empty($agent_goods_bind_goods)) { $goods_agent_admin_id = array_column($agent_goods_bind_goods, 'goods_agent_admin_id'); $where = [ 'id' => $goods_agent_admin_id, 'province_id' => $order->province_id ]; $admin = Admin::findOne(array_merge($where, [ 'area_level' => 1, 'city_id' => $order->city_id, 'district_id' => $order->district_id ])); if (empty($admin)) { $admin = Admin::findOne(array_merge($where, [ 'area_level' => 2, 'city_id' => $order->city_id ])); if (empty($admin)) { $admin = Admin::findOne(array_merge($where, [ 'area_level' => 3 ])); } } if (!empty($admin)) { $agent_rebate = $value['total_price'] * ($supplier_rate / 100) * ($goods_agent_percent / 100); $StoreShareMoney = StoreShareMoney::find()->where(['user_id' => $admin->saas_user_id, 'store_id' => $order->store_id, 'order_id' => $order_id, 'type' => 1]) ->andWhere(['like', 'desc', '产品代理佣金发放'])->one(); if(!$StoreShareMoney){ //给用户增加佣金 $SaasUser = SaasUser::findOne($admin->saas_user_id); $SaasUser->share_profit = ($SaasUser->share_profit * 1) + ($agent_rebate * 1); if (!$SaasUser->save()) { throw new \Exception(json_encode($SaasUser->errors)); } $StoreShareMoney = new StoreShareMoney(); $StoreShareMoney->user_id = $SaasUser->id; $StoreShareMoney->store_id = $order->store_id; $StoreShareMoney->profit = $goods_agent_percent; $StoreShareMoney->total_price = $value['total_price']; $StoreShareMoney->desc = '产品代理佣金发放,代理商品' . $value['name']; $StoreShareMoney->order_id = $order_id; $StoreShareMoney->created_at = time(); $StoreShareMoney->status = StoreShareMoney::STATUS_STORE_ORDER; $StoreShareMoney->type = StoreShareMoney::TYPE_GOODS_AGENT; $StoreShareMoney->commission = $agent_rebate; $StoreShareMoney->is_send = 1; if (!$StoreShareMoney->save()) { throw new \Exception(json_encode($StoreShareMoney->errors)); } } } } } //计算上门安装佣金 $install_log = AgentGoodsInstallLog::findOne(['order_detail_id' => $value['id'], 'status' => 2, 'is_need_install' => 1, 'order_type' => AgentGoodsInstallLog::ORDER_TYPE_NORMAL]); if (!empty($install_log)) { $admin = Admin::findOne($install_log->goods_agent_admin_id); if (!empty($admin)) { $agent_rebate = $value['total_price'] * ($supplier_rate / 100) * ($goods_agent_install_percent / 100); $StoreShareMoney = StoreShareMoney::find()->where(['user_id' => $admin->saas_user_id, 'store_id' => $order->store_id, 'order_id' => $order_id, 'type' => 1]) ->andWhere(['like', 'desc', '上门安装佣金发放'])->one(); if(!$StoreShareMoney){ //给用户增加佣金 $SaasUser = SaasUser::findOne($admin->saas_user_id); $SaasUser->share_profit = ($SaasUser->share_profit * 1) + ($agent_rebate * 1); if (!$SaasUser->save()) { throw new \Exception(json_encode($SaasUser->errors)); } $StoreShareMoney = new StoreShareMoney(); $StoreShareMoney->user_id = $SaasUser->id; $StoreShareMoney->store_id = $order->store_id; $StoreShareMoney->profit = $goods_agent_install_percent; $StoreShareMoney->total_price = $value['total_price']; $StoreShareMoney->desc = '产品代理上门安装佣金发放,安装商品' . $value['name']; $StoreShareMoney->order_id = $order_id; $StoreShareMoney->created_at = time(); $StoreShareMoney->status = StoreShareMoney::STATUS_STORE_ORDER; $StoreShareMoney->type = StoreShareMoney::TYPE_GOODS_AGENT; $StoreShareMoney->commission = $agent_rebate; $StoreShareMoney->is_send = 1; if (!$StoreShareMoney->save()) { throw new \Exception(json_encode($StoreShareMoney->errors)); } } } } } $t->commit(); } catch (\Exception $e) { $t->rollBack(); \Yii::error($e->getMessage()); } } public function workerLevel($order_id) { try { if(isset($order_id->id)){ $order = $order_id; }else{ $order = Order::findOne($order_id); } $order_id = $order->id; if(!$order || !$order->is_sale){ return; } $WorkerOrderExt = WorkerOrderExt::findOne(['order_id' => $order_id]); if(!$WorkerOrderExt || !$WorkerOrderExt->worker_id){ return; } $item = Worker::findOne($WorkerOrderExt->worker_id); if ($item) { $order_ext_price_num = WorkerOrderExt::find()->alias('woe') ->leftJoin(['o' => Order::tableName()], 'o.id = woe.order_id') ->where(['woe.worker_id' => $item['id'], 'woe.status_ext' => 100]) ->andWhere(['o.is_delete' => 0, 'o.is_sale' => 1]) ->select('o.total_price, o.order_type_ext')->asArray()->all(); $order_num = 0; $order_price = 0; foreach ($order_ext_price_num as $order_item) { if (in_array($order_item['order_type_ext'], [0, Order::ORDER_TYPE_EXT_WORKER_FIRST_PAY])) { ++$order_num; } $order_price += $order_item['total_price']; } $worker_level = WorkerLevel::find()->where(['store_id' => $order->store_id, 'status' => 1, 'is_delete' => 0]) ->andWhere(['AND', ['<=', 'order_money', $order_price],['<=', 'order_count', $order_price], ['>', 'level', $item['level']]]) ->orderBy('level DESC') ->asArray()->one(); if ($worker_level) { $current_level = $worker_level['level']; if ($current_level) { $worker = Worker::findOne($item['id']); $worker->level = $current_level; $worker->save(); } } } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], 'worker.log'); } } /** * 自动取消预约订单 */ public function orderBook($order_id) { try { $order = Order::find()->where(['id' => $order_id, 'is_delete' => 0, 'is_pay' => 0]) ->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CANCEL]) ->andWhere(['in', 'order_type', [1, 2]])->one(); /* @var Order[] $orders */ if (!empty($order)) { $autoCancleTime = static::getAutoCancelTime($order->store_id); if ($autoCancleTime > 0 && time() - $order->created_at >= $autoCancleTime) { $order->trade_status = Order::ORDER_FLOW_CANCEL; $order->updated_at = time(); $order->save(); } } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } public function level($order_id) { try { if(isset($order_id->id)){ $order = Order::findOne($order_id->id); }else{ $order = Order::findOne($order_id); } $order_id = $order->id; if(!$order || !$order->is_sale || !$order->user_id){ return; } $sum = Order::find()->alias('o') ->where(['o.user_id' => $order->user_id, 'o.is_sale' => 1, 'o.is_delete' => 0, 'o.trade_status' => 3]) ->leftJoin(['r' => OrderRefund::find()->where(['is_delete' => 0, 'store_id' => $order->store_id])->select('*')], "r.order_id=o.id") ->andWhere([ 'or', 'isnull(r.id)', ['r.type' => 2], ['in', 'r.status', [2, 3]] ]) ->sum('o.pay_price'); $user = User::findOne($order->user_id); //查会员等级 $levelList = Level::find() ->where(['store_id' => $order->store_id, 'is_delete' => 0, 'status' => 1]) // 增加开启了累计消费升级的条件 ->andWhere(['like', 'upgrade_conditions' , Level::UPGRADE_CONDITIONS_MONEY]) ->orderBy(['money' => SORT_DESC, 'id' => SORT_DESC]) ->asArray()->all(); //调整会员等级 foreach ($levelList as $level) { if ($sum >= $level['money']) { if ($user['level'] < $level['level']) { $user->level = $level['level']; if ($user->save()) { \Yii::error(['会员自动升级==============>', $user->id]); } } break; } } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 处理过期优惠券 */ public function couponTimeout($UserCoupon_id) { try { $coupon_list = UserCoupon::find()->alias('uc')->where([ 'uc.id' => $UserCoupon_id, 'uc.is_use' => 0, 'uc.is_delete' => 0, 'uc.is_expire' => 0, ])->leftJoin(['c' => Coupon::tableName()], 'c.id=uc.coupon_id')->select('uc.id, uc.begin_time, uc.end_time, c.expire_type')->asArray()->all(); if (empty($coupon_list)) { return; } foreach ($coupon_list as $value) { $delay = 0; if ($value['expire_type'] == 1 ) { if ($value['end_time'] < 1) { continue; } else { if (time() >= $value['end_time']) { UserCoupon::updateAll(['is_expire' => 1, 'updated_at' => time()], [ 'id' => $value['id'], ]); continue; }else{ $delay = $value['end_time'] - time(); } } } if ($value['expire_type'] == 2) { if (time() >= strtotime(date('Y-m-d 23:59:59', $value['end_time']))) { UserCoupon::updateAll(['is_expire' => 1, 'updated_at' => time()], [ 'id' => $value['id'], ]); continue; }else{ $delay = strtotime(date('Y-m-d 23:59:59', $value['end_time'])) - time(); } } if($delay){ \queue_push(new \app\jobs\CouponTimeoutJob(['userCoupon_id' => $UserCoupon_id]), $delay); } } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 用户自动成为分销商 * @param $user_id integer 用户id */ public function userAutoBecomeShare($user_id) { try { $item = User::findOne($user_id); if(!$item){ return; } $store_id = $item->store_id; $share_basic_setting = Option::get(OptionSetting::SHARE_BASIC_SETTING, $store_id, OptionSetting::SHARE_GROUP_NAME, '')['value']; $share_basic_setting = json_decode($share_basic_setting, true); // $share_basic_setting['share_condition']['value'] = $share_basic_setting['share_condition']['value'] ?? 2; $share_basic_setting['auto_share_val']['value'] = $share_basic_setting['auto_share_val']['value'] ?? 0; //判断无需审核且消费0元成为分销商条件 if (intval($share_basic_setting['share_condition']['value']) === 2 && floatval($share_basic_setting['auto_share_val']['value']) <= 0) { //筛出已经成为分销商的用户 $filter_user_id = Share::find()->where(['user_id' => $user_id, 'is_delete' => 0, 'store_id' => $store_id, 'status' => 1])->select('user_id')->one(); if($filter_user_id){ return; } //筛出已经被删除的分销商 $filter_delete_user_id = Share::find()->where(['user_id' => $user_id, 'is_delete' => 1, 'store_id' => $store_id, 'status' => 1])->select('user_id')->one(); if($filter_delete_user_id){ return; } $share = Share::findOne(['user_id' => $item->id, 'is_delete' => 0, 'store_id' => $store_id]); if (!$share) { $share = new Share(); $share->mobile = ''; $share->name = ''; $share->is_delete = 0; $share->user_id = $item->id; $share->created_at = time(); } $share->status = 1; $share->store_id = $store_id; if ($share->save()) { $item->time = time(); $item->is_distributor = 1; $item->save(); } } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 认养成熟超时自动设置农场代采 */ public function AdoptOrderMature($order) { try { if(is_numeric($order)){ $order = AdoptOrderInfo::findOne($order); } $time = time(); $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $order->store_id,]); $mature_overtime = $AdoptSetting->mature_overtime; $mature_time = $time - ($mature_overtime * 86400); if($order->pick_method == AdoptOrderInfo::ORDER_FLOW_NO_PICK){ if($order->mature_time <= $mature_time){ $order->pick_method = AdoptOrderInfo::ORDER_FLOW_OTHER_PICK; $order->pick_time = $order->mature_time + ($mature_overtime * 86400); $order->pick_treatment_method = AdoptOrderInfo::ORDER_FLOW_PICK_STORAGE; $order->pick_treatment_method_time = time(); $order->save(); }else{ \queue_push(new \app\jobs\order\AdoptOrderMatureJob(['order_id' => $order->id]), $mature_time - $order->mature_time); } } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 认养入库超时自动设置保管 */ public function AdoptOrderStorage($order) { try { if(is_numeric($order)){ $order = AdoptOrderInfo::findOne($order); } $time = time(); $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $order->store_id,]); $storage_overtime = $AdoptSetting->storage_overtime; $storage_time = $time - ($storage_overtime * 86400); if($order->is_preserve == AdoptOrderInfo::ORDER_FLOW_WAIT_PRESERVE){ if($order->storage_time <= $storage_time){ $order->is_preserve = AdoptOrderInfo::ORDER_FLOW_PRESERVE; $order->preserve_time = $order->storage_time + ($storage_overtime * 86400); $order->save(); }else{ \queue_push(new \app\jobs\order\AdoptOrderStorageJob(['order_id' => $order->id]), $storage_time - $order->storage_time); } } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 认养免费保管结束开始计费 */ public function AdoptOrderBillingStart($order) { try { if(is_numeric($order)){ $order = AdoptOrderInfo::findOne($order); } $time = time(); $AdoptSetting = AdoptSetting::findOne(['store_id' => $order->store_id,]); $free_preserve_time = $AdoptSetting->free_preserve_time; $preserve_time = $time - ($free_preserve_time * 86400); if($order->is_preserve == AdoptOrderInfo::ORDER_FLOW_PRESERVE){ if($order->preserve_time <= $preserve_time){ $order->billing_start_time = $order->preserve_time + ($free_preserve_time * 86400); $order->save(); }else{ \queue_push(new \app\jobs\order\AdoptOrderBillingStartJob(['order_id' => $order->id]), $preserve_time - $order->preserve_time); } } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 认养成熟超时提示信息 (提示成熟超时要自动代采入库) */ public function AdoptOrderMatureTips($order) { try { if(is_numeric($order)){ $order = AdoptOrderInfo::findOne($order); } $time = time(); $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $order->store_id,]); $mature_overtime_tips = $AdoptSetting->mature_overtime_tips; $mature_time = $time - ($mature_overtime_tips * 86400); $mature_overtime = $AdoptSetting->mature_overtime; if($order->is_sms_mature){ return; } if($order->pick_method == AdoptOrderInfo::ORDER_FLOW_NO_PICK){ if($order->mature_time <= $mature_time){ $order_relevance = Order::findOne(['id'=>$order->order_id]); $order->is_sms_mature = 1; $order->save(); //查看已成熟几天。几天后系统自动设置 $day1 = ceil(time() - $order->mature_time); $day2 = $mature_overtime -$day1; NoticeSend::Adopt($order_relevance->user_id, $order->mobile, $order_relevance->order_no, $order->name, 1,$day1,$day2); }else{ \queue_push(new \app\jobs\order\AdoptOrderMatureTipsJob(['order_id' => $order->id]), $mature_time - $order->mature_time); } } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 认养入库超时提示信息 (提示入库过期要自动保管) */ public function AdoptOrderStorageTips($order) { try { if(is_numeric($order)){ $order = AdoptOrderInfo::findOne($order); } $time = time(); $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $order->store_id,]); $storage_overtime_tips = $AdoptSetting->storage_overtime_tips; $storage_time = $time - ($storage_overtime_tips * 86400); $storage_overtime = $AdoptSetting->mature_overtime; if($order->is_sms_storage){ return; } if($order->is_preserve == AdoptOrderInfo::ORDER_FLOW_WAIT_PRESERVE){ if($order->storage_time <= $storage_time){ $order_relevance = Order::findOne(['id'=>$order->order_id]); $order->is_sms_storage = 1; $order->save(); //查看已成熟几天。几天后系统自动设置 $day1 = ceil(time() - $order->storage_time); $day2 = $storage_overtime -$day1; NoticeSend::Adopt($order_relevance->user_id, $order->mobile, $order_relevance->order_no, $order->name, 2,$day1,$day2); }else{ \queue_push(new \app\jobs\order\AdoptOrderStorageTipsJob(['order_id' => $order->id]), $storage_time - $order->storage_time); } } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 认养免费保管提示信息 (提示从开始保管时间算免费保管超时) */ public function AdoptOrderBillingTips($order) { try { if(is_numeric($order)){ $order = AdoptOrderInfo::findOne($order); } $time = time(); $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $order->store_id,]); $preserve_time_tips = $AdoptSetting->free_preserve_time_tips; $preserve_time = $time - ($preserve_time_tips * 86400); $preserve = $AdoptSetting->free_preserve_time; if($order->is_sms_preserve){ return; } if($order->is_preserve == AdoptOrderInfo::ORDER_FLOW_PRESERVE){ if($order->preserve_time <= $preserve_time){ $order_relevance = Order::findOne(['id'=>$order->order_id]); $order->is_sms_preserve = 1; $order->save(); //查看已成熟几天。几天后系统自动设置 $day1 = ceil(time() - $order->preserve_time); $day2 = $preserve -$day1; NoticeSend::Adopt($order_relevance->user_id, $order->mobile, $order_relevance->order_no, $order->name, 3,$day1,$day2); }else{ \queue_push(new \app\jobs\order\AdoptOrderBillingTipsJob(['order_id' => $order->id]), $preserve_time - $order->preserve_time); } } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 自动取消认养配送订单 */ public function adoptCostOrderCancel($order) { try { if(is_numeric($order)){ $order = AdoptCostOrder::findOne($order); } $time = time(); $over_time = Option::get(OptionSetting::STORE_DELIVERY_TIME, $order->store_id)['value']; if (!$over_time) { $over_time = 1; } $over_day = $time - ($over_time * 86400); if($order->is_pay || $order->trade_status == Order::ORDER_FLOW_CANCEL || $order->pay_type == 2){ return; } if($order->created_at <= $over_day){ $t = \Yii::$app->db->beginTransaction(); if ($order->order_type == 1) { $adopt_order = AdoptOrderInfo::find()->where(['order_id' => $order->order_id, 'is_delete' => 0, 'store_id' => $order->store_id,])->one(); $adopt_order->updateCounters(['harvest_weight' => $order->weight]); } $order->trade_status = Order::ORDER_FLOW_CANCEL; $order->updated_at = time(); if (!$order->save()) { $t->rollBack(); return; } $t->commit(); }else{ \queue_push(new \app\jobs\order\AdoptCostOrderCancelJob(['order_id' => $order->id]), $over_day - $order->created_at); } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 认养配送订单自动收货 */ public function adoptCostOrderConfirm($order) { try { if(is_numeric($order)){ $order = AdoptCostOrder::findOne($order); } $time = time(); $delivery_time = Option::get(OptionSetting::STORE_DELIVERY_TIME, $order->store_id)['value']; $delivery_time = $time - ((int)$delivery_time * 86400); if($order->is_delete || $order->trade_status == Order::ORDER_FLOW_CONFIRM){ return; } if($order->send_time <= $delivery_time){ $adopt_order_info = AdoptOrderInfo::find()->alias('aoi') ->where([ 'aoi.order_id' => $order->order_id, 'aoi.store_id' => $order->store_id, 'aoi.harvest_weight' => 0 ])->one(); if ($adopt_order_info->harvest_weight == 0) { $adopt_order = Order::find()->alias('o') ->where([ 'o.id' => $order->order_id, 'o.store_id' => $order->store_id, 'o.order_type' => 5, ])->one(); $adopt_order->trade_status = Order::ORDER_FLOW_CONFIRM; $adopt_order->save(); $goods = Goods::findOne(OrderDetail::findOne(['order_id' => $order->order_id])->goods_id); NoticeSend::AdoptOrderStateChange($adopt_order->user_id, $adopt_order_info->mobile, $adopt_order->order_no, $goods->name, 13); } AdoptCostOrder::updateAll(['trade_status' => Order::ORDER_FLOW_CONFIRM, 'confirm_time' => time()], ['id' => $order->id]); if ($order->pay_type == 2) { $order->is_pay = 1; $order->save(); } }else{ \queue_push(new \app\jobs\order\AdoptCostOrderConfirmJob(['order_id' => $order->id]), $delivery_time - $order->send_time); } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } //处理秒杀逻辑 如果15分钟内没有支付订单,则恢复库存 public function seckillActivityOrder($order) { try { if(is_numeric($order)){ $order = SeckillActivityOrderLog::findOne($order); } $order_relevance = Order::findOne(['id'=>$order->order_id]); if($order->is_delete){ return; } $timeout = time() - (60 * 15); if($order_relevance->trade_status == 1 || $order_relevance->is_pay == 0){ if($order->created_at <= $timeout){ $goods = SeckillActivityGoods::findOne(['is_delete' => 0, 'goods_id' => $order->goods_id, 'activity_id' => $order->activity_id]); // 只退了销量 if ($goods) { $goods->sale_num -= $order->num; if (!$goods->save()) { throw new \Exception(json_encode($goods->errors)); } } // 退库存 $order_detail_relevance = OrderDetail::findOne(['id' => $order->order_detail_id]); $goods->numAdd(array_column(json_decode($order_detail_relevance->attr,true),'attr_id'), $order_detail_relevance->num); $order->is_delete = 1; if (!$order->save()) { throw new \Exception(json_encode($order->errors)); } }else{ \queue_push(new \app\jobs\order\SeckillActivityOrderJob(['order_id' => $order->id]), 60*15); } } } catch (\Exception $e) { \Yii::error("秒杀逻辑处理" . $e->getMessage()); // return [ // 'code' => 1, // 'msg' => $e->getMessage() // ]; } } //处理拼团逻辑 如果15分钟内没有支付订单,则恢复库存,如果对应时间未拼团则退款 public function PtActivityOrder($order) { try { if(is_numeric($order)){ $order = PtActivityOrder::findOne($order); } $PtActivityOrderDetail = PtActivityOrderDetail::findOne(['order_id' => $order->id]); if($order->is_pay != 1 || $order->trade_status != 0 || $order->is_pt_finish != 0 || $order->pt_number != 0){ return; } $activity = PtActivity::findOne($PtActivityOrderDetail['activity_id']); $split_time = ($activity->split_time * 60 * 60); $delay = 0; if (time() - $split_time < $order['pay_time']) { $delay = $order['pay_time'] - (time() - $split_time); } $delay1 = 0; if ($activity->end_time > time()) { $delay1 = $activity->end_time - time(); } if($delay || $delay1){ $delay = $delay < $delay1 ? $delay : $delay1; } //已经过期,需要失败处理 if (!$delay) { $pt_order_ = PtActivityOrder::find()->where(['is_pay' => 1]) ->andWhere(['OR', ['id' => $order['id']], ['pt_number' => $order['id']]]) ->select('id')->asArray()->all(); foreach ($pt_order_ as $item) { $order = PtActivityOrder::findOne($item['id']); if ($order->head_integral > 0 && intval($order->head_integral_status) === 1) { $res = AccountLog::saveLog($order->user_id, floatval($order->head_integral), AccountLog::TYPE_INTEGRAL, AccountLog::LOG_TYPE_INCOME, 3, $order->id, "商城拼团失败,退还开团支付积分,订单号为:{$order->order_no}。"); if (!$res) { debug_log('开团积分退款失败' . json_encode($res), 'ptOrderLog.log'); } $order->head_integral_status = 2; } $order->is_pt_finish = 2; $order->save(); } $form = new PtActivityOrderForm(); $result = $form->loserHandle($order['id']); if ($result['code'] !== 0) { throw new \Exception($result['msg']); } }else{ \queue_push(new \app\jobs\order\PtActivityOrderJob(['order_id' => $order->id]), $delay); } } catch (\Exception $e) { \Yii::error("拼团逻辑处理" . $e->getMessage()); // return [ // 'code' => 1, // 'msg' => $e->getMessage() // ]; } } /** * 同城配送订单处理 */ public function LocalDeliveryOrder($DeliveryInfo) { try{ if(is_numeric($DeliveryInfo)){ $DeliveryInfo = DeliveryInfo::findOne($DeliveryInfo); } if(!$DeliveryInfo || !$DeliveryInfo->is_local || !$DeliveryInfo->local_status || !$DeliveryInfo->rider_id){ return; } $order = Order::findOne(['order_no' => $DeliveryInfo->order_no]); if(!$order || $order->is_delete || (!$order->is_pay && $order->pay_type != Order::PAY_TYPE_COD)){ return; } \Yii::warning(['---- Order Event BEGIN 自动派单发放开始 localDeliveryOrder ----']); $time = time(); $local_type = Option::get(OptionSetting::STORE_LOCAL_TYPE, $DeliveryInfo->store_id, 'store')['value']; $local_type = Option::get(OptionSetting::STORE_LOCAL_TYPE, $DeliveryInfo->store_id, 'pay', $local_type)['value']; $store_id = 0; if (intval($DeliveryInfo->is_store_delivery_type)) { $store_id = $DeliveryInfo->store_id; } $values = Option::find()->where([ 'store_id' => $store_id, 'group' => OptionSetting::LOCAL_DELIVERY_GROUP_NAME, 'name' => OptionSetting::LOCAL_DELIVERY_SETTING ])->select('value')->one(); if ($values) { $local_setting = json_decode($values->value, true); } else { $local_setting = null; } $open_auth = false; if (!empty($local_setting['send_type']['value'])) {//商城没有配送 if ($local_setting['send_type']['value'] == 'auto') { //开启自动派单 $open_auth = true; } } if (!$open_auth) { return false; } // if ($local_setting['send_type']['value'] != 'auto') { //未开启自动派单 // \Yii::warning(['---- Order Event BEGIN 平台未开启自动派单 localDeliveryOrder ----']); // return false; // } $default_time = $local_setting['default_time']['value']; //默认预计送达所消耗的时间,例:30分钟 $delay = 0; if($order->delivery_time > bcadd($time, bcmul($default_time, 60, 0), 0)){ $delay = $order->delivery_time - bcadd($time, bcmul($default_time, 60, 0), 0); } if(!$delay){ $this->autoSendDeliveryOrder($order); }else{ \queue_push(new \app\jobs\order\LocalDeliveryOrderJob(['DeliveryInfo_id' => $DeliveryInfo->id]), $delay); } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 模块名:autoSendDeliveryOrder * 代码描述:平台自配的同城订单自动派单 * 作者:WPing丶 * 请求方式:GET * 创建时间:2023/07/04 16:39:37 * @param object order */ public function autoSendDeliveryOrder($order) { try{ \Yii::warning(['---- Order Event BEGIN 平台自动派单开始,order_id='.$order->id.' ----']); if ($order->is_delivery != 1) { //非同城订单 \Yii::warning(['---- Order Event BEGIN 非同城订单,order_id='.$order->id.' ----']); return false; } $values = Option::find()->where([ 'store_id' => 0, 'group' => OptionSetting::LOCAL_DELIVERY_GROUP_NAME, 'name' => OptionSetting::LOCAL_DELIVERY_SETTING ])->select('value')->one(); if ($values) { $local_setting = json_decode($values->value, true); } else { $local_setting = null; } $default_time = $local_setting['default_time']['value']; if ((time() + ($default_time * 60)) < $order->delivery_time) { //期望送达时间提前30分钟分配订单 \Yii::warning(['---- Order Event BEGIN 当前订单时间小于期望送达时间,order_id='.$order->id.' ----']); return false; } $delivery_info = DeliveryInfo::findOne(['order_no' => $order->order_no]); if ($delivery_info->is_local == DeliveryInfo::IS_LOCAL_NO) { //非平台自配 \Yii::warning(['---- Order Event BEGIN 当前订单非平台自配订单,order_id='.$order->id.' ----']); return false; } if ($delivery_info->is_store_delivery_type == 1) { //商城自配 \Yii::warning(['---- Order Event BEGIN 当前订单为商城自配订单,order_id='.$order->id.' ----']); return false; } $option = Option::find()->where(['store_id' => 0, 'group' => OptionSetting::LOCAL_DELIVERY_GROUP_NAME, 'name' => OptionSetting::LOCAL_DELIVERY_SETTING])->select('value')->one(); if ($option) { $setting = json_decode($option->value, true); } else { $setting = null; } if ($setting['send_type']['value'] != 'auto') { //未开启自动派单 \Yii::warning(['---- Order Event BEGIN 平台未开启自动派单,order_id='.$order->id.' ----']); return false; } //获取可配送此订单的配送员列表 $query = LocalDeliveryCourier::find() ->where([ 'is_delete' => 0, 'state' => 2, 'status' => 1 ]); /* 2023年7月6日20:17:11 */ //配送员筛选条件:配送订单自动推送给负责本村的配送员 $province_id = $order->province_id ? $order->province_id : 0; $city_id = $order->city_id ? $order->city_id : 0; $district_id = $order->district_id ? $order->district_id : 0; $town_id = $order->town_id ? $order->town_id : 0; $village_id = $order->village_id ? $order->village_id : 0; $area = '[{"province_id":"' . $province_id . '","city_id":"' . $city_id . '","district_id":"' . $district_id . '","town_id":"' . $town_id . '","village_id":"' . $village_id . '"}]'; $query->andWhere(['area' => $area]); /* end */ //删除该配置 默认为店铺模式 // if ($setting['delivery_type']['value'] == "store") { //店铺模式:开启该模式只有店铺的“专属配送员”或者“平台配送员”才可以配送此订单 $query->andWhere(['type' => 1]); // } $courier_list = $query->asArray()->all(); $courier_list_new = []; foreach ($courier_list as $courier) { //获取当前配送员正在配送的订单数量 $now_order_num = DeliveryInfo::find() ->alias('di') ->leftJoin(['o' => Order::tableName()], 'o.order_no = di.order_no') ->where(['di.rider_id' => $courier['id'], 'di.is_local' => 1, 'o.is_pay' => 1]) ->andWhere([ 'or', ['o.trade_status' => 0], ['o.trade_status' => 1] ])->count(); if ($courier['max_num'] == 0 || $now_order_num < $courier['max_num']) { //排除掉订单满载的配送员 $work_time = json_decode($courier['work_time'],true); $begin_time = strtotime(date('Y-m-d ').$work_time[0]['begin_time']); $end_time = strtotime(date('Y-m-d ').$work_time[0]['end_time']); if (time() >= $begin_time && time() <= $end_time ) {//排除不在上岗时间的配送员 $courier_list_new[] = $courier; } } } if (count($courier_list_new) == 0) { //没有满足条件的配送员 \Yii::warning(['---- Order Event BEGIN 平台没有满足条件的配送员,order_id='.$order->id.' ----']); return false; } //随机选择一名天选打工人给他分配订单(目前是随机,后期再优化) $t = \Yii::$app->db->beginTransaction(); //开始事务 $randomKey = array_rand($courier_list_new); $chosen_worker = $courier_list_new[$randomKey]; $delivery_info->rider_id = $chosen_worker['id']; $delivery_info->rider_name = $chosen_worker['real_name']; $delivery_info->rider_mobile = $chosen_worker['mobile']; $delivery_info->local_status = DeliveryInfo::LOCAL_STATUS_WAITING; $delivery_info->rush_time = time(); if (!$delivery_info->save()) { \Yii::warning(['---- Order Event BEGIN 存delivery_info表失败,order_id='.$order->id.' ----']); $t->rollBack(); //事务回滚 return false; } $order->send_time = time(); $order->trade_status = 2; if (!$order->save()) { \Yii::warning(['---- Order Event BEGIN 存order表失败,order_id='.$order->id.' ----']); $t->rollBack(); //事务回滚 return false; } \Yii::warning(['---- Order Event END 自动派单成功,order_id='.$order->id.' ----']); $t->commit(); //事务执行 } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } //分销商升级 public function shareLevel($store_id, $user_id) { try { // 1 parent_id = u // 2 parent_id = a a parent_id = u // 3 parent_id = b c parent_id = d d parent_id = u $share_level = ShareLevel::find()->where(['store_id' => $store_id, 'is_delete' => ShareLevel::SHARE_NOT_DELETE, 'status' => ShareLevel::STATUS_ON, 'is_auto_upgrade' => ShareLevel::AUTO_UPGRADE]) ->orderBy('level ASC')->asArray()->all(); foreach ($share_level as $level) { $user_info = Share::find()->where(['store_id' => $store_id, 'user_id' => $user_id, 'status' => Share::SHARE_AUDIT_PASS, 'is_delete' => Share::SHARE_NOT_DELETE]) ->andWhere(['<', 'level', $level['level']])->select('id, user_id, level')->asArray()->one(); $level['type'] = intval($level['type']); $open = false; $type = 0; $value = 0; //团队人数 if ($level['type'] === ShareLevel::TYPE_MEMBER) { $user_count = User::find()->where(['old_parent_id' => $user_info['user_id'], 'is_delete' => User::USER_NOT_DELETE, 'store_id' => $store_id, 'is_distributor' => 1]) ->select('id')->count() ?? 0; if (intval($level['value']) <= $user_count) { $open = true; $type = ShareLevel::TYPE_MEMBER; $value = $user_count; } } //累计佣金 if ($level['type'] === ShareLevel::TYPE_COMMISSION) { $user_share_money = UserShareMoney::find()->where(['type' => 0, 'is_delete' => 0, 'user_id' => $user_info['user_id'], 'store_id' => $store_id]) ->select('money')->sum('money') ?? 0; if (intval($level['value']) <= $user_share_money) { $open = true; $type = ShareLevel::TYPE_COMMISSION; $value = $user_share_money; } } //累计提现佣金 if ($level['type'] === ShareLevel::TYPE_SEND_COMMISSION) { $cash_table_name = Cash::tableName(); $sql = "SELECT SUM(`price`) FROM {$cash_table_name} WHERE `cash_type` = :is_cash_type_share AND `user_id` = {$user_info['user_id']} AND ( `status` = :status_given AND ( ( `type` = :type_wx AND `pay_type` = :pay_type_wx AND ( `wx_cash_type` = :wx_cash_type_old AND `wx_cash_status` = :wx_cash_status_success ) OR ( `wx_cash_type` = :wx_cash_type_new AND `wx_cash_state` = 'SUCCESS' ) ) OR `pay_type` <> :pay_type_wx ) OR `status` = :status_hand )"; $user_share_money_ = \Yii::$app->db->createCommand($sql, [ 'is_cash_type_share' => Cash::IS_CASH_TYPE_SHARE, 'status_given' => Cash::STATUS_GIVEN, 'type_wx' => Cash::TYPE_WX, 'pay_type_wx' => Cash::PAY_TYPE_WX, 'wx_cash_type_old' => Cash::WX_CASH_TYPE_OLD, 'wx_cash_status_success' => Cash::WX_CASH_STATUS_SUCCESS, 'wx_cash_type_new' => Cash::WX_CASH_TYPE_NEW, 'status_hand' => Cash::STATUS_HAND ])->queryScalar(); // $user_share_money_ = UserShareMoney::find()->where(['type' => 1, 'is_delete' => 0, 'user_id' => $user_info['user_id'], 'store_id' => $store_id]) // ->select('money')->sum('money') ?? 0; if (intval($level['value']) <= $user_share_money_) { $open = true; $type = ShareLevel::TYPE_SEND_COMMISSION; $value = $user_share_money_; } } //累计消费金额 if ($level['type'] === ShareLevel::TYPE_AMOUNT) { $user_pay_price = Order::find()->where(['is_pay' => 1, 'is_delete' => 0, 'user_id' => $user_info['user_id'], 'store_id' => $store_id]) ->andWhere(['trade_status' => [Order::ORDER_FLOW_NO_SEND, Order::ORDER_FLOW_SEND, Order::ORDER_FLOW_CONFIRM]]) ->select('pay_price')->sum('pay_price') ?? 0; if (intval($level['value']) <= $user_pay_price) { $open = true; $type = ShareLevel::TYPE_AMOUNT; $value = $user_pay_price; } } if ($open) { $share = Share::findOne($user_info['id']); $share->level = $level['level']; if ($share->save()) { $log = new ShareLevelLog(); $log->level = $level['level']; $log->old_level = $user_info['level']; $log->type = $type; $log->value = $value; $log->store_id = $store_id; $log->user_id = $user_info['user_id']; $log->save(); } } } return [ 'code' => 0, 'msg' => '处理完成' ]; } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } //更新订单毛利润 public function OrderGrossProfit($order) { try{ if(is_numeric($order)){ $order = Order::findOne($order); } if(!$order || $order->is_gross_profit == 1){ return; } $list = [$order->toArray()]; $form = new \app\modules\admin\models\CostProfitListForm(); $form->commonData($list); foreach ($list as $item) { Order::updateAll(['is_gross_profit' => 1, 'gross_profit' => $item['profit']], ['id' => $item['id']]); } } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } /** * 成为股东自动成为分销商 */ public function shareHolderAutoBecomeShare($share_holder) { try{ $user_id = $share_holder['user_id']; $store_id = $share_holder['store_id']; $share = Share::findOne(['user_id' => $user_id, 'is_delete' => 0, 'store_id' => $store_id]); if ($share && $share->status == 1) { return; } if (!$share || $share->status == 2) { $share = new Share(); $share->user_id = $user_id; $share->mobile = ''; $share->name = ''; $share->is_delete = 0; $share->store_id = $store_id; } $share->status = 1; $share->created_at = time(); $share->save(); $user = User::findOne($user_id); $user->time = time(); $user->is_distributor = 1; $user->save(); } catch (\Exception $e) { debug_log([__METHOD__, __LINE__, $e->getMessage()], __CLASS__ . '.log'); } } // 获取排队序号 public static function getQueueSort($queue_id, $queue_log_id, $total = false) { $total_count = 0; if ($total) { $total_count = QueueLog::find() ->where(['queue_id' => $queue_id]) ->count(); } $current_sort = QueueLog::find() ->where(['queue_id' => $queue_id]) ->andWhere(['<', 'id', $queue_log_id]) ->count(); return ['total_count' => $total_count, 'current_sort' => $current_sort + 1]; } // 排队免单 public function orderQueueSeceiver($order) { $queue_details = QueueLog::find()->where(['order_id' => $order['id'], 'is_send' => 0])->all(); if (!$queue_details) { return; } foreach ($queue_details as $queue_detail) { $this->orderQueueSelfSeceiver($order, $queue_detail); $this->orderQueueShareSeceiver($order, $queue_detail); // 首先查是否存在排队 debug_log([__LINE__, $queue_detail->id], 'queue_receiver.log'); $t = \Yii::$app->db->beginTransaction(); try { $id = 0; while (1) { $queue_log = QueueLog::find() ->where('id > :id AND `queue_id` = :queue_id AND `is_meet` = 0 AND `status` != 2', [':id' => $id, ':queue_id' => $queue_detail->queue_id]) ->orderBy('`id` ASC')->one(); if (!$queue_log) { debug_log([__LINE__, $queue_log, $queue_detail->id, '没有排队商品'], 'queue_receiver.log'); break; // throw new \Exception('没有排队商品'); } $id = $queue_log->id; debug_log([__LINE__, $queue_log->id, $queue_detail->id], 'queue_receiver.log'); if(!$queue_detail->cashback_type){ if ($queue_log->order_id == $order['id']) { debug_log('自己购买的订单跳过', 'queue_receiver.log'); continue; // throw new \Exception('自己购买的订单跳过'); } } $user = User::findOne($queue_log->user_id); if (!$user) { debug_log($queue_log->id . '用户不存在' . $queue_log->user_id, 'queue_receiver.log'); continue; // throw new \Exception('用户不存在'); } // 判断当前已返多少 $queue_detail->is_send = 1; $queue_detail->send_time = time(); if(!$queue_detail->cashback_type){ $queue_detail->order_money_pool = 0; } $rate = $queue_detail->rate; if ($rate <= 0) { debug_log('返现比例为0', 'queue_receiver.log'); break; // throw new \Exception('返现比例为0'); } $icount = 1; if($queue_detail->cashback_type){ $money_queue = QueueLog::find() ->where('`queue_id` = :queue_id AND `status` != 2 AND `order_money_pool` > 0 AND `order_id` != :order_id', [':queue_id' => $queue_log->queue_id, ':order_id' => $queue_log->order_id]) ->andWhere(['order_id' => Order::find()->select('id')->where(['is_sale' => 1])]) ->orderBy('`id` ASC')->all(); $money_sum = array_sum(array_column($money_queue, 'order_money_pool')); if($money_sum < $queue_detail->cashback_money){ debug_log($money_sum . '不够返利门槛金额' . $queue_detail->cashback_money, 'queue_receiver.log'); continue; // throw new \Exception($money_sum . '不够返利门槛金额' . $queue_detail->cashback_money); } $icount = floor($money_sum / $queue_detail->cashback_money); } debug_log([__LINE__, $queue_log->id, $queue_detail->id, $icount, $money_sum, $queue_detail->cashback_money], 'queue_receiver.log'); while ($icount >= 1) { $icount--; if($queue_log->is_meet == 1){ debug_log($queue_log->id . '返利已完成' . $queue_log->is_meet, 'queue_receiver.log'); break; } debug_log([__LINE__, $queue_log->id, $queue_detail->id, $icount], 'queue_receiver.log'); $from_queue_id = 0; $from_queue_list = []; $getMoney = 0; $t1 = \Yii::$app->db->beginTransaction(); if($queue_detail->cashback_type){ try{ foreach ($money_queue as $mqi => $mqv) { if($mqv->order_money_pool <= 0){ continue; } $oneMoney = 0; $getMoney += $mqv->order_money_pool; $mqvMoney = $mqv->order_money_pool; if($getMoney >= $queue_detail->cashback_money){ $oneMoney = 1; $mqv->order_money_pool = $getMoney - $queue_detail->cashback_money; $mqvMoney = $mqvMoney - $mqv->order_money_pool; }else{ $mqv->order_money_pool = 0; $mqv->is_send = 1; $mqv->send_time = time(); } if($queue_detail->id == $mqv->id){ $from_queue_id = $queue_detail->id; } $mqvMoney > 0 && $from_queue_list[] = ['from_queue_log_id' => $mqv->id, 'order_id' => $mqv->order_id, 'money' => $mqvMoney]; if(!$mqv->save()){ throw new \Exception('扣减金额错误' . $mqv->id . array_shift($mqv->getFirstErrors())); } if($oneMoney){ break; } } if(!$oneMoney){ debug_log($getMoney . '贡献金额不足' . $queue_detail->cashback_money, 'queue_receiver.log'); $t1->rollback(); break; } if(!$from_queue_id && $from_queue_list){ $from_queue_id = $from_queue_list[0]['from_queue_log_id']; } debug_log([__LINE__, $queue_log->id, $queue_detail->id, $icount, $from_queue_list], 'queue_receiver.log'); } catch (\Exception $ex) { $t1->rollback(); \Yii::error($ex); throw new \Exception($ex->getLine() . $ex->getMessage()); } } $queue_money = round(($queue_detail->total_money * $rate / 100), 2); if (($queue_money + $queue_log->returned_money) > $queue_log->total_money) { $queue_money = $queue_log->total_money - $queue_log->returned_money; $queue_log->returned_money = $queue_log->total_money; $queue_log->is_meet = 1; $queue_log->status = 1; $queue_log->over_time = time(); } if (($queue_money + $queue_log->returned_money) == $queue_log->total_money) { $queue_log->returned_money = $queue_log->total_money; $queue_log->is_meet = 1; $queue_log->status = 1; $queue_log->over_time = time(); } if (($queue_money + $queue_log->returned_money) < $queue_log->total_money) { $queue_log->returned_money += $queue_money; $queue_log->status = 3; } $before_price = 0; $after_price = 0; if(!$queue_log->cashback_time){ // 添加记录 $before_price = $user->free_money; $user->updateCounters(['free_money' => $queue_money]); $after_price = $user->free_money; $user->updateCounters(['total_free_money' => $queue_money]); // 增加余额 AccountLog::saveLog($queue_log->user_id, $queue_money, AccountLog::TYPE_BALANCE, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order['id'], '订单'.$order['order_no'].'免单返现'); } $queue_account_log = new QueueAccountLog(); if($queue_log->cashback_time){ $queue_account_log->is_temp = 1; } $queue_account_log->store_id = $order['store_id']; $queue_account_log->user_id = $queue_log->user_id; $queue_account_log->order_id = $queue_log->order_id; $queue_account_log->amount = $queue_money; $queue_account_log->desc = '免单返现'; $queue_account_log->before =$before_price; $queue_account_log->after =$after_price; $queue_account_log->log_type = 1; $queue_account_log->type = 0; $queue_account_log->created_at = time(); $queue_account_log->queue_id = $queue_log->id; $queue_account_log->from_queue_id = $from_queue_id ? $from_queue_id : $queue_detail->id; $queue_account_log->from_queue_list = json_encode($from_queue_list); if(!$queue_account_log->save()){ $t1->rollback(); throw new \Exception('$queue_account_log $save 0 ' . array_shift($queue_account_log->getFirstErrors()) . json_encode($queue_account_log->attributes)); } $queue_detail->save(); $queue_log->save(); //整返 if($queue_log->is_meet){ $queue_account_log_list = QueueAccountLog::findAll(['queue_id' => $queue_log->id, 'is_temp' => 1]); foreach($queue_account_log_list as $qal){ $qal->is_temp = 0; $qal->before = $user->free_money; $qal->after = $user->free_money + $qal->amount; $qal->save(); // 添加记录 $user->updateCounters(['free_money' => $qal->amount, 'total_free_money' => $qal->amount]); $qal_order = Order::findOne($qal->order_id); $order_no = (string)$qal_order->order_no; // 增加余额 AccountLog::saveLog($queue_log->user_id, $qal->amount, AccountLog::TYPE_BALANCE, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $qal->order_id, '订单'.$order_no.'免单返现'); } } $t1->commit(); } if(!$queue_detail->cashback_type){ break; } } $t->commit(); } catch (\Throwable $e) { $t->rollBack(); debug_log([__LINE__, $e->getMessage()], 'queue_receiver.log'); \Yii::error($e); } if($queue_detail->cashback_type){ break; } } } // 返自身分账 public function orderQueueSelfSeceiver($order, $queue_detail) { // 首先查是否存在排队 $t = \Yii::$app->db->beginTransaction(); try { // $queue_log = QueueLog::find() // ->where('`queue_id` = :queue_id AND `is_meet` = 0 AND `status` != 2 AND `user_id` = :user_id', [':queue_id' => $queue_detail->queue_id, ':user_id' => $queue_detail->user_id]) // ->orderBy('`id` ASC FOR UPDATE')->one(); $queue_log = QueueLog::find() ->where('`id` = :id AND `is_meet` = 0 AND `status` != 2 AND `user_id` = :user_id', [':id' => $queue_detail->id, ':user_id' => $queue_detail->user_id]) ->orderBy('`id` ASC FOR UPDATE')->one(); if (!$queue_log) { throw new \Exception('没有排队商品'); } if ($queue_detail->self_bili <= 0) { throw new \Exception('比例为0'); } $user = User::findOne($queue_log->user_id); if (!$user) { throw new \Exception('用户不存在'); } $rate = $queue_detail->self_bili; $queue_money = round(($queue_detail->total_money * $rate / 100), 2); if (($queue_money + $queue_log->returned_money) > $queue_log->total_money) { $queue_money = $queue_log->total_money - $queue_log->returned_money; $queue_log->returned_money = $queue_log->total_money; $queue_log->is_meet = 1; $queue_log->status = 1; $queue_log->over_time = time(); } if (($queue_money + $queue_log->returned_money) == $queue_log->total_money) { $queue_log->returned_money = $queue_log->total_money; $queue_log->is_meet = 1; $queue_log->status = 1; $queue_log->over_time = time(); } if (($queue_money + $queue_log->returned_money) < $queue_log->total_money) { $queue_log->returned_money += $queue_money; $queue_log->status = 0; // 自身返利不进入进行中,还在排队中 } // 添加记录 $before_price = $user->free_money; $user->updateCounters(['free_money' => $queue_money]); $after_price = $user->free_money; $user->updateCounters(['total_free_money' => $queue_money]); // 增加余额 AccountLog::saveLog($queue_log->user_id, $queue_money, AccountLog::TYPE_BALANCE, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order['id'], '订单'.$order['order_no'].'免单返现'); $queue_account_log = new QueueAccountLog(); $queue_account_log->store_id = $order['store_id']; $queue_account_log->user_id = $queue_log->user_id; $queue_account_log->order_id = $queue_log->order_id; $queue_account_log->amount = $queue_money; $queue_account_log->desc = '免单返现-自身消费'; $queue_account_log->before = $before_price; $queue_account_log->after = $after_price; $queue_account_log->log_type = 1; $queue_account_log->type = 0; $queue_account_log->created_at = time(); $queue_account_log->queue_id = $queue_log->id; $queue_account_log->from_queue_id = $queue_detail->id; $queue_account_log->save(); $queue_log->save(); $t->commit(); } catch (\Throwable $e) { $t->rollBack(); debug_log($e->getMessage(), 'queue_receiver_self.log'); } } public function orderQueueShareSeceiver($order, $queue_detail) { $t = \Yii::$app->db->beginTransaction(); try { // 首先找上级 $user = User::findOne($order->user_id); if (!$user) { throw new \Exception('用户不存在'); } if ($user->old_parent_id == 0) { throw new \Exception('用户没有上级'); } $parent_user = User::findOne($user->old_parent_id); if (!$parent_user) { throw new \Exception('上级用户不存在'); } $queue_log = QueueLog::find() ->where('`queue_id` = :queue_id AND `is_meet` = 0 AND `status` != 2 AND `user_id` = :user_id', [':queue_id' => $queue_detail->queue_id, ':user_id' => $parent_user->id]) ->orderBy('`id` ASC FOR UPDATE')->one(); if (!$queue_log) { throw new \Exception('没有排队商品'); } if ($queue_detail->share_bili <= 0) { throw new \Exception('比例为0'); } $rate = $queue_detail->share_bili; $queue_money = round(($queue_detail->total_money * $rate / 100), 2); if (($queue_money + $queue_log->returned_money) > $queue_log->total_money) { $queue_money = $queue_log->total_money - $queue_log->returned_money; $queue_log->returned_money = $queue_log->total_money; $queue_log->is_meet = 1; $queue_log->status = 1; $queue_log->over_time = time(); } if (($queue_money + $queue_log->returned_money) == $queue_log->total_money) { $queue_log->returned_money = $queue_log->total_money; $queue_log->is_meet = 1; $queue_log->status = 1; $queue_log->over_time = time(); } if (($queue_money + $queue_log->returned_money) < $queue_log->total_money) { $queue_log->returned_money += $queue_money; $queue_log->status = 3; } // 添加记录 $before_price = $user->free_money; $parent_user->updateCounters(['free_money' => $queue_money]); $after_price = $user->free_money; $parent_user->updateCounters(['total_free_money' => $queue_money]); // 增加余额 AccountLog::saveLog($queue_log->user_id, $queue_money, AccountLog::TYPE_BALANCE, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order['id'], '订单'.$order['order_no'].'免单返现'); $queue_account_log = new QueueAccountLog(); $queue_account_log->store_id = $order['store_id']; $queue_account_log->user_id = $queue_log->user_id; $queue_account_log->order_id = $queue_log->order_id; $queue_account_log->amount = $queue_money; $queue_account_log->desc = '免单返现-推荐返利'; $queue_account_log->before =$before_price; $queue_account_log->after =$after_price; $queue_account_log->log_type = 1; $queue_account_log->type = 0; $queue_account_log->created_at = time(); $queue_account_log->queue_id = $queue_log->id; $queue_account_log->from_queue_id = $queue_detail->id; $queue_account_log->save(); $queue_log->save(); $t->commit(); } catch (\Throwable $e) { $t->rollBack(); debug_log($e->getMessage(), 'queue_receiver_share.log'); } } public function sendGrowthValue($order){ $setting = Option::get('growth_setting',$order->store_id,'level',''); if(!empty($setting)){ $setting['value'] = json_decode($setting['value'],true); } // 未设置 或者 设置消费成长值为0 的时候直接返回 if(empty($setting) || $setting['value']['buy_give'] <= 0){ return true; } $amount = floor(bcmul($order->total_price,$setting['value']['buy_give'] / 100,2)); return UserGrowthValueLog::setLog($order->store_id,$order->user_id,UserGrowthValueLog::LOG_TYPE_ADD,$amount,UserGrowthValueLog::TYPE_BUY,"{$order->order_no}消费获赠{$amount}成长值"); } }