where(['is_gross_profit' => 0])->limit(10)->asArray()->all(); $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 $ex) { \Yii::error($ex); } } public function shareLevel($store_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_arr = Share::find()->where(['store_id' => $store_id, 'status' => Share::SHARE_AUDIT_PASS, 'is_delete' => Share::SHARE_NOT_DELETE]) ->andWhere(['<', 'level', $level['level']])->select('id, user_id, level')->asArray()->all(); $level['type'] = intval($level['type']); foreach ($user_arr as $item) { $open = false; $type = 0; $value = 0; //团队人数 if ($level['type'] === ShareLevel::TYPE_MEMBER) { $user_count = User::find()->where(['parent_id' => $item['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' => $item['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) { $user_share_money_ = UserShareMoney::find()->where(['type' => 1, 'is_delete' => 0, 'user_id' => $item['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' => $item['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($item['id']); $share->level = $level['level']; if ($share->save()) { $log = new ShareLevelLog(); $log->level = $level['level']; $log->old_level = $item['level']; $log->type = $type; $log->value = $value; $log->store_id = $store_id; $log->user_id = $item['user_id']; $log->save(); } } } } return [ 'code' => 0, 'msg' => '处理完成' ]; } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } public function storeWxOrderShipping() { try{ $form = new \app\modules\admin\models\WechatThirdForm(['store_id' => $this->store_id]); $form->storeWxOrderShipping($this->store_id); } catch (\Exception $ex) { // \Yii::error($ex); } } public function otherThird() { // 处理商户进件状态 $this->handleMerchant(); $this->handleMerchant(1); } /** * 执行奖金池自动发放 * @return void */ public function reportPool() { //自动检查奖金池是否需要新增 $this->autoCheckPool(); // 处理奖金池自动发放 $this->autoReportPool(); } public function bonusPool() { } public function autoReportPool() { $ReportPoolArray = ReportPool::find()->where(['store_id'=>$this->store_id]) ->andWhere(['is_send'=>0]) ->andWhere(['!=','reward_amount',0]) ->andWhere(['<=', 'end_time',time()]) // ->andWhere(['<=', 'start_time',time()]) ->orderBy('id asc') ->asArray() ->all(); if(empty($ReportPoolArray)){ return; } \Yii::error('---------------------- REPORT POOL BEHAVIOR START------------------' . $this->store_id . '--' . count($ReportPoolArray)); if (!empty($ReportPoolArray)) { foreach ($ReportPoolArray as $ReportPoolItem) { $report_info_num = ReportInfo::find()->where(['store_id' => $ReportPoolItem['store_id'], 'pool_id'=> $ReportPoolItem['id'], 'status' => 1])->one(); if (!$report_info_num){ debug_log('奖金池没有报单,奖金池id:' . $ReportPoolItem['id']); continue; } //发放奖励到每个level中 //查看所有奖励记录的积分 $report_bonus_sum = ReportPoolLevel::find() ->where(['store_id' => $ReportPoolItem['store_id'], 'pool_id' => $ReportPoolItem['id']]) ->sum('money'); $report_level_list = ReportPoolLevel::find() ->where(['store_id' => $ReportPoolItem['store_id'], 'pool_id' => $ReportPoolItem['id']]) ->asArray() ->all(); foreach ($report_level_list as $key => $report_level_item){ // 总积分/奖励金额 * 个人奖励积分 //奖励金额计算 $reward_amount = $report_bonus_sum / $ReportPoolItem['reward_amount'] * $report_level_item['money']; //发放奖励到用户表当中记录 $user = User::findOne($report_level_item['user_id']); $user->updateCounters(['global_money_total' => $reward_amount, 'global_money' => $reward_amount]); $report_level_info = ReportPoolLevel::findOne($report_level_item['id']); $report_level_info->is_send = 1; $report_level_info->dividend_money = $reward_amount; $report_level_info->send_time = time(); if (!$report_level_info->save()){ debug_log('分发用户id:'.$report_level_info->id.'奖金池id:'.$ReportPoolItem['id']); } } //奖金池也设置已完成 ReportPool::updateAll(['is_send'=>1,'send_time'=>time()],['id' => $ReportPoolItem['id']]); //报单列表更新已完成 ReportInfo::updateAll(['is_send'=>1,'send_time'=>time()],['pool_id' => $ReportPoolItem['id']]); } } \Yii::error('---------------------- REPORT POOL BEHAVIOR END------------------'); return false; } /** * 检查奖金池是否需要新增 * @return void */ public function autoCheckPool() { $list = ReportPool::find()->where(['store_id'=>$this->store_id]) ->andWhere(['>=', 'end_time',time()]) ->andWhere(['<=', 'start_time',time()]) ->andWhere(['is_send'=>0]) ->orderBy('id asc') ->asArray() ->one(); if(!$list){ $report_setting = ReportSetting::findOne(['store_id' => $this->store_id]); if (!$report_setting->dividend_day){ debug_log('未设置奖金池分红周期'); return; } //如果奖金池不存在就新增奖池 $pool_info = new ReportPool(); $pool_info->store_id = $this->store_id; $pool_info->start_time = time(); $pool_info->end_time = time() + $report_setting->dividend_day * 24 * 60 * 60; $pool_info->created_at = time(); $pool_info_copy = ReportPool::find()->where(['store_id'=>$this->store_id]) ->orderBy('id desc') ->one(); if ($pool_info_copy){ $pool_info->number = $pool_info_copy->number+1; }else{ $pool_info->number =1; } if (!$pool_info->save()){ debug_log('奖金池新增失败'); } } } public function handleMerchant($is_yunst = 0) { $list = MerchantInfo::find()->where(['!=', 'state', Merchant::APPLYMENT_STATE_FINISHED]) ->andWhere(['!=', 'state', Merchant::APPLYMENT_STATE_CANCELED]) ->andWhere(['>', 'status', 0]) ->andWhere(['bind_store_id' => $this->store_id, 'is_yunst' => $is_yunst, 'is_delete' => 0])->asArray()->all(); if(empty($list)){ return; } \Yii::error('---------------------- HANDLE MERCHANT BEHAVIOR START------------------' . $this->store_id . '--' . count($list)); if (!empty($list)) { try { if ($is_yunst) { $merchant = new \app\utils\yunst\src\Merchant();//通联支付 } else { $merchant = new Merchant(); } } catch (\Exception $e) { \Yii::error(['---------------------- HANDLE MERCHANT BEHAVIOR CONFIG ERROR------------------', $e->getMessage()]); return; } foreach ($list as $value) { if ($is_yunst) { $res = $merchant->queryMerchantStatus($value['applyment_id']);//通联支付 } else { $res = $merchant->queryApplyment($value['applyment_id'], $value['business_code']); if (isset($res['code']) && isset($res['msg'])) { \Yii::warning(['<=================> 未获取到申请单信息', $res, $value['business_code']]); continue; } } \Yii::warning(['<=================> 获取到申请单信息', $res, $value['business_code']]); $merchant_info = MerchantInfo::findOne($value['id']); //通联支付 start if ($is_yunst) { $merchant_info->state = (string)$res['data']['auditstatus']; if ($res['data']['auditstatus'] == '00'){ $status = 0; }elseif ($res['data']['auditstatus'] == '01'){ $status = 1; }elseif ($res['data']['auditstatus'] == '02'){ $status =3; } elseif ($res['data']['auditstatus'] == '03'){ $status =2; } elseif ($res['data']['auditstatus'] == '04'){ $status =2; } $merchant_info->status = $status; //通联支付end } else { $merchant_info->state = (string)$res['applyment_state']; $merchant_info->status = Merchant::$valid_state_status[$res['applyment_state']]; if ($res['applyment_state'] === 'APPLYMENT_STATE_CANCELED') {//已撤销 $merchant_info->refuse_desc = "申请单已被撤销,请重新申请"; } } $merchant_info->sign_url = ""; $merchant_info->refuse_desc = ""; //通联支付 start if ($is_yunst) { if ($res['data']['auditstatus'] == '03' || $res['data']['auditstatus'] == '04' ) {//已撤销 $merchant_info->refuse_desc = $res['subMsg']; } //通联支付 end } else { if (!empty($res['sign_url']) && in_array($res['applyment_state'], ["APPLYMENT_STATE_TO_BE_SIGNED", "APPLYMENT_STATE_TO_BE_CONFIRMED"])) { $merchant_info->status = 1; $merchant_info->sign_url = json_encode([ 'applyment_state_msg' => $res['applyment_state_msg'], 'sign_url' => $res['sign_url'] ]); } //待用户验证 if ($res['applyment_state'] == Merchant::APPLYMENT_STATE_REJECTED) { if($res['audit_detail']){ $refuse_desc = []; foreach ($res['audit_detail'] as $idetail) { $refuse_desc[] = $idetail['field_name'] . ':' . $idetail['reject_reason']; } $merchant_info->refuse_desc .= implode(';;;', $refuse_desc); } } $merchant_info->sub_mch_id = $res['sub_mchid']; } //通联支付 start if ($is_yunst) { if ($res['data']['auditstatus'] == '02') { $merchant_info->sub_mch_id = $res['data']['merid']; $store_info = Store::findOne(['id' => $merchant_info->store_id]); $store_info->cusid = $res['data']['merid']; $store_info->save(); } } //通联支付 end if ($merchant_info->save()) { //如果已经完成并且又商户号则开始替换商城配置信息 if ($res['sub_mchid'] && $res['applyment_state'] == Merchant::APPLYMENT_STATE_FINISHED) { $WechatConfig = WechatConfig::find()->where(['store_id' => $merchant_info->bind_store_id])->one(); if(empty($WechatConfig)){ $WechatConfig = new WechatConfig; $WechatConfig->store_id = $merchant_info->bind_store_id; $WechatConfig->created_at = time(); $WechatConfig->updated_at = time(); $WechatConfig->app_id = '0'; $WechatConfig->app_secret = '0'; } $WechatConfig->mch_id = $res['sub_mchid']; $res = $WechatConfig->save(); } elseif (empty($res['sub_mchid']) && $res['applyment_state'] == Merchant::APPLYMENT_STATE_FINISHED) { $merchant_info->status = 2; $merchant_info->state = Merchant::APPLYMENT_STATE_REJECTED; $merchant_info->refuse_desc = Json::encode([ 'field' => "subject_type", 'reject_reason' => "进件已完结,请重新提交资料信息" ]); } // \Yii::warning(['<=================> 更新申请单信息失败', $value['business_code'], $res]); } } } \Yii::error('---------------------- HANDLE MERCHANT BEHAVIOR END------------------'); return false; } /** * 门店收益计算 */ 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 handleCoupon() { // \Yii::warning('---- COUPON BEHAVIOR START ----'); $coupon_list = UserCoupon::find()->alias('uc')->where([ 'uc.is_use' => 0, 'uc.is_delete' => 0, 'uc.is_expire' => 0, 'uc.store_id' => $this->store_id ])->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)) { // \Yii::warning('无可操作优惠券数据'); return; } foreach ($coupon_list as $value) { 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; } } } 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; } } } // \Yii::warning('---- COUPON BEHAVIOR END ----'); } /** * 订单自动收货 (废弃) */ private function orderConfirm() { $time = time(); $delivery_time = (Option::get(OptionSetting::STORE_DELIVERY_TIME, $this->store_id, 0)['value']); if ($delivery_time !== null) { $delivery_time = $time - ((int)$delivery_time * 86400); //不处理视频号小店订单 $field_order_id = VideoShopOrderExt::find()->where(['store_id' => $this->store_id, 'is_delete' => 0])->select('order_id')->column(); $order_confirm = Order::find()->where([ 'is_delete' => 0, 'trade_status' => Order::ORDER_FLOW_SEND, 'store_id' => $this->store_id ])->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CONFIRM])->andWhere(['<=', 'send_time', $delivery_time])->andWhere(['NOT IN', 'id', $field_order_id])->all(); foreach ($order_confirm as $k => $v) { /** * @var Order $v */ //如果是代理配送 且上门安装,用户没有对商品确认收货则不可确认收货 $order_detail = OrderDetail::findAll(['order_id' => $v->id]); $is_can_confirm = true; foreach ($order_detail as $detail) { $is_can_confirm_sub = ((bool)AgentGoodsInstallLog::findOne(['order_detail_id' => $detail->id, 'status' => [0, 1], 'is_need_install' => 1, 'order_type' => AgentGoodsInstallLog::ORDER_TYPE_NORMAL])); if ($is_can_confirm_sub) { $is_can_confirm = false; } } //如果是同城配送平台自配方式,判断骑手是否送达,如果未送达则不可以确认收货 $delivery_info = DeliveryInfo::findOne(['order_no' => $v->order_no]); if ($delivery_info) { if($delivery_info->local_status != DeliveryInfo::LOCAL_STATUS_CONFIRM) { $is_can_confirm = false; } } if ($is_can_confirm) { Order::updateAll(['trade_status' => Order::ORDER_FLOW_CONFIRM, 'confirm_time' => time()], ['id' => $v->id]); if ($v->pay_type == 2) { $v->is_pay = 1; $v->save(); } $t = \Yii::$app->db->beginTransaction(); if($delivery_info->local_status == DeliveryInfo::LOCAL_STATUS_CONFIRM) { /* 骑手完成订单后发放收入 */ $courier = LocalDeliveryCourier::findOne(['id' => $delivery_info->rider_id, 'is_delete' => 0, 'state' => 2]); //同城配送设置相关 $store_id = 0; if (intval($delivery_info->is_store_delivery_type)) { $store_id = $courier->store_id; } $values = Option::find()->where([ 'store_id' => $store_id, 'group' => OptionSetting::LOCAL_DELIVERY_GROUP_NAME, 'name' => OptionSetting::LOCAL_DELIVERY_SETTING ])->select('value')->one(); $local_setting = json_decode($values->value, true); if (!empty($courier)) { if ($store_id > 0) { $local_setting['default_cost']['value'] = -1; } $amount = (float)$local_setting['default_cost']['value'] == -1 ? $delivery_info->fee : (float)$local_setting['default_cost']['value']; $log = LocalDeliveryLog::saveLog($courier->saas_user_id, $amount, 1, 1, $v->id, "骑手配送收入:" . $amount . "元"); if (!$log) {//发放骑手佣金报错 \Yii::warning('---- ORDER CONFIRM 订单完成发放骑手收入失败,order_id='.$v->id.' ----'); $t->rollBack(); //事务回滚 continue; } } } $t->commit(); } } } } /** * 处理过了售后期且没有售后的订单 */ public function orderSend($type = 0, $order_id = [], $store_id = 0, $after_sale_time = 0, $is_handle_video_order = 0) { $time = time(); if ($type) { $sale_time = $time - ((int)$after_sale_time * 86400); $where = [ 'and', ['o.store_id' => $store_id], ['o.id' => $order_id], ['o.is_delete' => 0, 'o.trade_status' => Order::ORDER_FLOW_CONFIRM, 'o.is_sale' => 0], ['<=', 'o.confirm_time', $sale_time], ]; $this->store_id = $store_id; } else { $after_sale_time = Option::get(OptionSetting::STORE_AFTER_SALE_TIME, $this->store_id, 0)['value']; $sale_time = $time - ((int)$after_sale_time * 86400); $where = [ 'and', ['o.store_id' => $this->store_id], ['o.is_delete' => 0, 'o.trade_status' => Order::ORDER_FLOW_CONFIRM, 'o.is_sale' => 0], ['<=', 'o.confirm_time', $sale_time], ]; } //不处理视频号小店订单 $field_order_id = []; if ($is_handle_video_order) { $field_order_id = VideoShopOrderExt::find()->where(['store_id' => $this->store_id, 'is_delete' => 0])->select('order_id')->column(); } $order_list = Order::find()->alias('o') ->where($where)->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CANCEL])->andWhere(['NOT IN', 'o.id', $field_order_id]) ->leftJoin(OrderRefund::tableName() . ' r', "r.order_id = o.id and r.is_delete = 0") ->select(['o.*'])->groupBy('o.id') ->andWhere([ 'or', 'isnull(r.id)', ['r.type' => 2], ['in', 'r.status', [2, 3]] ])->offset(0)->limit(50)->asArray()->all(); $store_info = Store::findOne($this->store_id); $order_id_arr = []; try { $order_id_arr = $this->profitSharing($sale_time, $this->store_id); } catch (\Exception $e) { \Yii::warning('---- COUPON BEHAVIOR END分账失败 ----' . $e->getMessage()); } foreach ($order_list as $index => $value) { if (in_array($value['id'], $order_id_arr ?? [])) { continue; } try { //检测微信是否收货 Wechat::init($this->store_id); $app = Wechat::$wechat_mini; $form = new \app\modules\admin\models\WechatThirdForm(['store_id' => $this->store_id]); $order_ = Order::find()->where(['id' => $value['id']])->asArray()->one(); if($form->wxOrderStateIsConfirm($app, $order_)){ //如果没有添加成功分账接收人就完结分账 $share_receiver = SharingReceiver::findOne(['store_id' => $this->store_id, 'order_no' => $value['order_no']]); if (!$share_receiver) { $res = WechatShare::complete($value['transaction_id'], $value['id'], false, '分账完结', $this->store_id, $value['is_platform'] ); debug_log('分账完结_', 'wechatShare.log'); debug_log($res, 'wechatShare.log'); } } } catch (\Exception $e) { debug_log($e->getMessage(), 'wechatShare.log'); } Order::updateAll(['is_sale' => 1, 'updated_at' => time()], ['id' => $value['id']]); \app\models\ActivityRebateOrderNLog::priceInfoOrderId($value['id']); BonusPool::generalUserConsume($value['user_id'], $value['store_id']); BonusPool::sendTwoPlusOneTeamLevelShare($value['id']); BonusPool::sendArea($value['id']); BonusPool::userAuto2ShareHolder($value['id']); BonusPool::userSelfBuyGoods2ShareHolder($value['id']); $this->share_money($value['id']); $this->share_holder_money($value['id']); $this->give_integral($value['id']); $this->shop_share($value['id']); $this->league_price($value['id']); // 门店收益 if ($value['md_id'] > 0) { $this->handleMdProfit($value['id']); } BonusPool::sendRange($value['id']); // 奖金池补充奖金 BonusPool::poolPush($value['id']); $this->sendVideoGoodsProfit($value['id']); //代理发放佣金 $this->agencyPrice($value['id']); //产品代理发放佣金 $this->sendGoodsAgentMoney($value['id']); try { // 处理供应链平台商户号收款店铺结算 if ($value['is_use_platform_mch'] == 1 && $value['pay_type'] == 1) { $profit = $value['pay_price'] * $store_info->transfer_profit / 100; $price = $value['pay_price'] - $profit; Store::addMoney($store_info, $price, '用户下单', $value['id'], $value['user_id']); } } catch (\Exception $e) { // Todo } try { //服务人员分佣 $workerProfitSend = \app\modules\admin\models\worker\WorkerForm::workerProfitSend($value['id']); debug_log(['服务人员分佣', $value['id'], $workerProfitSend], __CLASS__ . '.log'); } catch (\Exception $e) { \Yii::error($e); } } } //分账 订单分账失败重新分账 public function profitSharing($sale_time, $store_id) { $order_id_arr = []; try { $SharingReceiver = SharingReceiver::find()->where(['is_pay' => SharingReceiver::PAY_WAIT])->andWhere(['store_id' => $store_id])->groupBy('order_no')->asArray()->all(); foreach ($SharingReceiver as $item) { $orderNoHead = substr($item['order_no'], 0, 2); $model = Order::find(); $where = []; switch ($orderNoHead) { case 'ML': case 'AL': //商盟会员购物订单 $model = Order::find(); $where = ['AND', [ 'order_no' => $item['order_no'], 'is_delete' => 0, 'trade_status' => Order::ORDER_FLOW_CONFIRM ], ['<=', 'confirm_time', $sale_time + 60]]; break; case 'SC': //当面付订单 $model = \app\plugins\scanCodePay\models\Order::find(); $where = [ 'order_no' => $item['order_no'], 'is_delete' => 0, 'is_pay' => 1 ]; break; } $order = $model->where($where)->one(); 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); } catch (\Exception $e) { \Yii::warning('---- COUPON BEHAVIOR END支付宝分账失败 ----' . $e->getMessage()); } } } } catch (\Exception $e) { \Yii::warning('---- COUPON BEHAVIOR END ----'); } return $order_id_arr; } private 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(in_array($item['type'], [SharingReceiver::RECEIVE_MERCHANT_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__); } } /** * 积分发放 */ private function give_integral($id) { $give = Order::findOne($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']]); $give->give_integral = 1; $give->save(); AccountLog::saveLog($giveUser->id, $integral, AccountLog::TYPE_INTEGRAL, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $give->id, '订单'.$give->order_no.'赠送积分'); } // 团长佣金结算 private 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(); } } } } /** * 分销订单佣金结算 * @param Order $order */ private function sendOrderProfit($order, $expire_day = 0) { if (!$order->share_order_profit) { \Yii::warning('订单佣金可分发值为0'); return; } $user_share = UserShareLog::find()->where(['user_id' => $order->user_id])->orderBy('created_at desc')->limit(1)->asArray()->one(); \Yii::warning($user_share); if (empty($user_share)) { \Yii::warning('订单佣金未找到分享关系'); return; } if ($expire_day > 0) { if ($order->pay_time - $user_share['created_at'] > $expire_day * 24 * 3600) { \Yii::warning('订单佣金分享关系已过期'); return; } } $user = User::findOne($user_share['parent_id']); if (!$user) { \Yii::warning('订单佣金未找到分享关系用户'); return; } if ($order->share_send_type == 2) { AccountLog::saveLog($user_share['parent_id'], $order->share_order_profit, 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($user_share['parent_id'], $order->share_order_profit, AccountLog::TYPE_BALANCE, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "商城订单佣金赠送余额, 订单号:{$order->order_no}"); } else { $user->updateCounters(['total_price' => doubleval($order->share_order_profit), 'price' => doubleval($order->share_order_profit)]); $order->updateCounters(['share_price' => doubleval($order->share_order_profit)]); UserShareMoney::set($order->share_order_profit, $user->id, $order->id, 0, 5, $order->store_id, 0); } } private function league_price($id){ $order = Order::findOne($id); $store = Store::findOne($this->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){ $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->updateCounters(['league_price' => floatval($order->take_price)]); SaaSLeaguePriceLog::setLeaguePriceLog( $order->store_id, $saas_user->id, $order->take_price, $before, SaaSLeaguePriceLog::TYPE_ORDER_REBATE, SaaSLeaguePriceLog::SEND_TYPE, SaaSLeaguePriceLog::ROLE_STORE, $order->id ); } } // 分销订单佣金结算 private function share_money($id) { $order = Order::findOne($id); if (!$order) { return; } if ($order->is_price != 0) { return; } //排除商盟订单 if($order->user_id == 0) { return; } $setting = Option::get('share_money_setting', $this->store_id); $setting = $setting ? Json::decode($setting['value']) : []; if (!$setting) { \Yii::warning('订单佣金发送:未开启分销设置1'); return; } //临时关系佣金发放 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("订单中临时关系佣金为空"); } $share_setting = Option::get('share_basic_setting', $this->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); } $order->is_price = 1; } // 一级佣金发放 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)]); } $order->is_price = 1; } // 二级佣金发放 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)]); } } } $order->save(); return; } // 等级分佣结算 private function share_holder_money($id) { $order = Order::findOne($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, $this->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, $this->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, $this->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, $this->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, $this->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, $this->store_id, 0); $order->updateCounters(['share_price' => doubleval($order->old_holder_third_price)]); } $order->save(); } private function money($parent_id, $money) { if ($parent_id == 0) { return ['code' => 1, 'parent_id' => 0]; } $parent = User::findOne(['id' => $parent_id]); if (!$parent) { return ['code' => 1, 'parent_id' => 0]; } $parent->updateCounters(['total_price' => $money, 'price' => $money]); return [ 'code' => 0, 'parent_id' => $parent->parent_id, ]; } /** * 分账 * @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_ADAPAY_WX, Order::PAY_TYPE_ADAPAY_ALIPAY]) && $this->is_yunst==0){ 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); //检测微信是否收货 Wechat::init($this->store_id); $app = WechatMini::getWechatConfig($this->store_id); if (!$app) { array_push($order_id_arr, $order->id); continue; } $form = new \app\modules\admin\models\WechatThirdForm(['store_id' => $this->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(); $res = $form->wxOrderStateIsConfirm($app, $order_); if(!$res){ array_push($order_id_arr, $order->id); continue; } $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([ '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 = 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]); $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']]); $this->saasUserPriceLog($order, [$receivers_share1]); $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]); $this->saasUserPriceLog($order, [$receivers_share1], true); $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]); } /** * 自动提现 * @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('66065100000219T'); $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('分账不存在,提现失败'); } } 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); $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']]); $this->saasUserPriceLog($order, [$receivers_share1]); } } 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); } } // 分账完结 \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(); debug_log('开始分账le'); debug_log($receivers_share); $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); //开始分账 debug_log('开始分账1'); debug_log($receivers_share1); //这里重新方法调用orderYunst来实现分账 $res = OrderYunst::share($order, $receivers_share1); \Yii::error(['adapayProfitSharingadapayProfitSharing11:', $res]); //通联分账 if ($res['code'] > 0) { debug_log('分账失败了'); debug_log($res); $faildDes = $res['msg']; $faildDes && $faildDes = addslashes('(失败:' . $faildDes . ')'); //分到平台 if($receivers_share1['type'] == 2){ debug_log('到这里了吧hahahah'); debug_log($res['res']); debug_log($res['msg']); debug_log($res['res']['yunst_order_no']); debug_log($res['res']['err_code']); debug_log($res['res']['err_code_des']); 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']]); continue; } sleep(1); //如果分账到账户失败再重试 $res = OrderYunst::shareToSaas($order, $receivers_share1); \Yii::error(['分到平台yunstProfitSharingadapayProfitSharing11:', $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']]); $this->saasUserPriceLog($order, [$receivers_share1]); //如果是分账成功自动提现 $this->autoCash($order_id); } } else { debug_log('分账成功了'); debug_log($res); $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); } } // 分账完结 \Yii::error(['<=======================> 订单号:' . $order->order_no . '-分账完结结果:']); } public function adapayShareToSelf() { $time = time(); $after_sale_time = Option::get(OptionSetting::STORE_AFTER_SALE_TIME, $this->store_id, 0)['value']; $sale_time = $time - (((int)$after_sale_time + 1) * 86400); $where = [ 'and', ['o.store_id' => $this->store_id], ['o.is_delete' => 0, 'o.trade_status' => Order::ORDER_FLOW_CONFIRM, 'o.is_sale' => 1, 'o.adapay_share_finish' => 0], ['<=', 'o.confirm_time', $sale_time], ['<>', 'o.adapay_payment_id', ''], ]; $query = Order::find()->alias('o') ->where($where)->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CANCEL]) ->offset(0)->limit(50); $order_list = $query->all(); foreach ($order_list as $index => $order) { $share = Adapay::shareToSelf($order); if($share['code'] == 0){ Order::updateAll(['adapay_share_finish' => 1], ['id' => $order['id']]); } } $this->adapayShareToSelfScanCodePayOrder(); $this->adapayShareToSelfReOrder(); } public function adapayShareToSelfScanCodePayOrder() { $time = time(); $after_sale_time = Option::get(OptionSetting::STORE_AFTER_SALE_TIME, $this->store_id, 0)['value']; $sale_time = $time - (((int)$after_sale_time + 1) * 1); $where = [ 'and', ['o.store_id' => $this->store_id], ['o.is_delete' => 0, 'o.trade_status' => Order::ORDER_FLOW_CONFIRM, 'o.adapay_share_finish' => 0], ['<=', 'o.pay_time', $sale_time], ['<>', 'o.adapay_payment_id', ''], ]; $query = \app\plugins\scanCodePay\models\Order::find()->alias('o') ->where($where)->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CANCEL]) ->offset(0)->limit(50); $order_list = $query->all(); foreach ($order_list as $index => $order) { $share = Adapay::shareToSelf($order); if($share['code'] == 0){ \app\plugins\scanCodePay\models\Order::updateAll(['adapay_share_finish' => 1], ['id' => $order['id']]); } } } public function adapayShareToSelfReOrder() { $time = time(); $after_sale_time = Option::get(OptionSetting::STORE_AFTER_SALE_TIME, $this->store_id, 0)['value']; $sale_time = $time - (((int)$after_sale_time + 1) * 1); $where = [ 'and', ['o.store_id' => $this->store_id], ['o.is_delete' => 0, 'o.adapay_share_finish' => 0], ['<=', 'o.pay_time', $sale_time], ['<>', 'o.adapay_payment_id', ''], ]; $query = ReOrder::find()->alias('o') ->where($where) ->offset(0)->limit(50); $order_list = $query->all(); foreach ($order_list as $index => $order) { $share = Adapay::shareToSelf($order); if($share['code'] == 0){ ReOrder::updateAll(['adapay_share_finish' => 1], ['id' => $order['id']]); } } } /** * 支付宝分账 * @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) { 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(); if (empty($receivers_share)) { \Yii::error('<=======================> 订单号:' . $order->order_no . '分账接收人为空'); return; } \Yii::warning($receivers_share); $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 = []; $res_arr[] = [ 'royalty_type' => 'transfer', 'trans_in_type' => 'userId', '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; } $res = AlipayProfit::settle($order->order_no, $order->alipay_trade_no, $res_arr, $order->store_id,'true', $is_app); // } \Yii::error(['<=======================> 订单号:' . $order->order_no . ', 分销请求分账结果:', $res]); if ($res['code'] > 0) { $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']]); $this->saasUserPriceLog($order, [$receiver]); } return; } SharingReceiver::updateAll(['updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS], ['id' => $receiver['id']]); $this->saasUserPriceLog($order, $receivers_share); $this->saasUserPriceLog($order, $receivers_share, true); } } /** * 自动取消预约订单 */ public function orderBook() { $orders = Order::find()->where(['is_delete' => 0, 'is_pay' => 0, 'store_id' => $this->store_id]) ->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CANCEL]) ->andWhere(['in', 'order_type', [1, 2]])->all(); /* @var Order[] $orders */ if (!empty($orders)) { foreach ($orders as $order) { if (time() - $order->created_at > 15 * 30) { $order->trade_status = Order::ORDER_FLOW_CANCEL; $order->updated_at = time(); $order->save(); } } } } public function workerLevel() { try { $worker_list = Worker::find()->where(['store_id' => $this->store_id, 'status' => Worker::STATUS_VALID])->select('id, level')->asArray()->all(); foreach ($worker_list as $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' => $this->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($e->getMessage(), 'worker.log'); } } public function level() { $time = time(); $after_sale_time = Option::get(OptionSetting::STORE_AFTER_SALE_TIME, $this->store_id, 0)['value']; $sale_time = $time - ((int)$after_sale_time * 86400); //查出所有有订单的会员 $userIds = Order::find()->alias('o')->select(['o.user_id', 'sum(o.pay_price) order_money']) ->where(['o.is_delete' => 0, 'o.store_id' => $this->store_id, 'o.trade_status' => 3]) ->andWhere(['<=', 'o.confirm_time', $sale_time]) ->andWhere(['>','o.user_id',0]) //新增user_id=0是商盟订单 ->leftJoin(['r' => OrderRefund::find()->where(['is_delete' => 0, 'store_id' => $this->store_id])->select('*')], "r.order_id=o.id") ->andWhere([ 'or', 'isnull(r.id)', ['r.type' => 2], ['in', 'r.status', [2, 3]] ]) ->groupBy('o.user_id'); $cacheKey = __METHOD__; if(cache()->get($cacheKey)){ $sale_time2 = $sale_time - 3 * 86400; $uids = (clone $userIds)->andWhere(['>=', 'o.confirm_time', $sale_time2])->all(); if(empty($uids)){ return; } $uidArr = array_column($uids, 'user_id'); $userIds->andWhere(['o.user_id' => $uidArr]); } cache()->set($cacheKey, 1, 86400); //查如上会员的当前等级金额 $userList = User::find() ->alias('u') ->select(['u.*', 'uids.order_money']) ->innerJoin(['uids' => $userIds], 'uids.user_id = u.id') ->andWhere('uids.order_money is not null') ->asArray()->all(); //查会员等级 $levelList = Level::find() ->where(['store_id' => $this->store_id, 'is_delete' => 0, 'status' => 1]) ->orderBy(['money' => SORT_DESC, 'id' => SORT_DESC]) ->asArray()->all(); //调整会员等级 foreach ($userList as $user) { foreach ($levelList as $level) { if ($user['order_money'] >= $level['money']) { if ($user['level'] < $level['level']) { $user_info = User::findOne($user['id']); $user_info->level = $level['level']; if ($user_info->save()) { \Yii::error(['会员自动升级==============>', $user_info->id]); } } break; } } } } /** * 认养成熟超时自动设置农场代采 */ public function AdoptOrderMature() { $time = time(); $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $this->store_id,]); $mature_overtime = $AdoptSetting->mature_overtime; $mature_time = $time - ($mature_overtime * 86400); $order_info = AdoptOrderInfo::find()->where([ 'is_delete' => 0, 'pick_method'=> AdoptOrderInfo::ORDER_FLOW_NO_PICK, 'is_mature' => AdoptOrderInfo::ORDER_FLOW_MATURE, 'store_id' => $this->store_id, ])->andWhere(['<=', 'mature_time', $mature_time])->all(); foreach ($order_info as $k => $v) { $v->pick_method = AdoptOrderInfo::ORDER_FLOW_OTHER_PICK; $v->pick_time = $v->mature_time + ($mature_overtime * 86400); $v->pick_treatment_method = AdoptOrderInfo::ORDER_FLOW_PICK_STORAGE; $v->pick_treatment_method_time = time(); $v->save(); } } /** * 认养入库超时自动设置保管 */ public function AdoptOrderStorage() { $time = time(); $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $this->store_id,]); $storage_overtime = $AdoptSetting->storage_overtime; $storage_time = $time - ($storage_overtime * 86400); $order_info = AdoptOrderInfo::find() ->where([ 'is_delete' => 0, 'is_mature' => AdoptOrderInfo::ORDER_FLOW_MATURE, 'is_storage' => AdoptOrderInfo::ORDER_FLOW_STORAGE, 'is_preserve' => AdoptOrderInfo::ORDER_FLOW_WAIT_PRESERVE, 'store_id' => $this->store_id, ]) ->andWhere(['!=', 'pick_method', AdoptOrderInfo::ORDER_FLOW_NO_PICK]) ->andWhere(['<=', 'storage_time', $storage_time])->all(); foreach ($order_info as $k => $v) { $v->is_preserve = AdoptOrderInfo::ORDER_FLOW_PRESERVE; $v->preserve_time = $v->storage_time + ($storage_overtime * 86400); $v->save(); } } /** * 认养免费保管结束开始计费 */ public function AdoptOrderBillingStart() { $time = time(); $AdoptSetting = AdoptSetting::findOne(['store_id' => $this->store_id,]); $free_preserve_time = $AdoptSetting->free_preserve_time; $preserve_time = $time - ($free_preserve_time * 86400); $order_info = AdoptOrderInfo::find()->where([ 'is_delete' => 0, 'is_preserve' => AdoptOrderInfo::ORDER_FLOW_PRESERVE, 'store_id' => $this->store_id, ])->andWhere(['<=', 'preserve_time', $preserve_time])->all(); foreach ($order_info as $k => $v) { $v->billing_start_time = $v->preserve_time + ($free_preserve_time * 86400); $v->save(); } } /** * 认养成熟超时提示信息 (提示成熟超时要自动代采入库) */ public function AdoptOrderMatureTips(){ $time = time(); $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $this->store_id,]); $mature_overtime_tips = $AdoptSetting->mature_overtime_tips; $mature_time = $time - ($mature_overtime_tips * 86400); $mature_overtime = $AdoptSetting->mature_overtime; $order_info = AdoptOrderInfo::find() ->where([ 'is_delete' => 0, 'is_mature' => AdoptOrderInfo::ORDER_FLOW_MATURE, 'pick_method'=> AdoptOrderInfo::ORDER_FLOW_NO_PICK, 'store_id' => $this->store_id,]) ->andWhere(['<=', 'mature_time', $mature_time])->andWhere(['is_sms_mature'=>0])->all(); if ($order_info){ foreach ($order_info as $k => $v) { $order_relevance = Order::findOne(['id'=>$v->order_id]); $v->is_sms_mature = 1; $v->save(); //查看已成熟几天。几天后系统自动设置 $day1 = ceil(time() - $v->mature_time); $day2 = $mature_overtime -$day1; NoticeSend::Adopt($this->user_id, $v->mobile, $order_relevance->order_no, $v->name, 1,$day1,$day2); } } } /** * 认养入库超时提示信息 (提示入库过期要自动保管) */ public function AdoptOrderStorageTips(){ $time = time(); $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $this->store_id,]); $storage_overtime_tips = $AdoptSetting->storage_overtime_tips; $storage_time = $time - ($storage_overtime_tips * 86400); $storage_overtime = $AdoptSetting->mature_overtime; $order_info = AdoptOrderInfo::find() ->where([ 'is_delete' => 0, 'is_mature' => AdoptOrderInfo::ORDER_FLOW_MATURE, 'is_storage' => AdoptOrderInfo::ORDER_FLOW_STORAGE, 'is_preserve' => AdoptOrderInfo::ORDER_FLOW_WAIT_PRESERVE, 'store_id' => $this->store_id, ]) ->andWhere(['!=', 'pick_method', AdoptOrderInfo::ORDER_FLOW_NO_PICK]) ->andWhere(['<=', 'storage_time', $storage_time])->andWhere(['is_sms_storage'=>0])->all(); if ($order_info){ foreach ($order_info as $k => $v) { $order_relevance = Order::findOne(['id'=>$v->order_id]); $v->is_sms_storage = 1; $v->save(); //查看已成熟几天。几天后系统自动设置 $day1 = ceil(time() - $v->storage_time); $day2 = $storage_overtime -$day1; NoticeSend::Adopt($this->user_id, $v->mobile, $order_relevance->order_no, $v->name, 2,$day1,$day2); } } } /** * 认养免费保管提示信息 (提示从开始保管时间算免费保管超时) */ public function AdoptOrderBillingTips(){ $time = time(); $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $this->store_id,]); $preserve_time_tips = $AdoptSetting->free_preserve_time_tips; $preserve_time = $time - ($preserve_time_tips * 86400); $preserve = $AdoptSetting->free_preserve_time; $order_info = AdoptOrderInfo::find()->where([ 'is_delete' => 0, 'is_preserve' => AdoptOrderInfo::ORDER_FLOW_PRESERVE, 'store_id' => $this->store_id, ])->andWhere(['<=', 'preserve_time', $preserve_time])->andWhere(['is_sms_preserve'=>0])->all(); if ($order_info){ foreach ($order_info as $k => $v) { $order_relevance = Order::findOne(['id'=>$v->order_id]); $v->is_sms_preserve = 1; $v->save(); //查看已成熟几天。几天后系统自动设置 $day1 = ceil(time() - $v->preserve_time); $day2 = $preserve -$day1; NoticeSend::Adopt($this->user_id, $v->mobile, $order_relevance->order_no, $v->name, 3,$day1,$day2); } } } /** * 认养配送订单自动收货 */ private function adoptCostOrderConfirm() { $time = time(); $delivery_time = Option::get(OptionSetting::STORE_DELIVERY_TIME, $this->store_id)['value']; $delivery_time = $time - ((int)$delivery_time * 86400); $order_confirm = AdoptCostOrder::find()->where([ 'is_delete' => 0, 'trade_status' => AdoptCostOrder::ORDER_FLOW_SEND, 'store_id' => $this->store_id, ])->andWhere(['<>', 'trade_status', AdoptCostOrder::ORDER_FLOW_CONFIRM])->andWhere(['<=', 'send_time', $delivery_time])->all(); foreach ($order_confirm as $k => $v) { /** * @var Order $v */ $adopt_order_info = AdoptOrderInfo::find()->alias('aoi') ->where([ 'aoi.order_id' => $v->order_id, 'aoi.store_id' => $this->store_id, 'aoi.harvest_weight' => 0 ])->one(); if ($adopt_order_info->harvest_weight == 0) { $adopt_order = Order::find()->alias('o') ->where([ 'o.id' => $v->order_id, 'o.store_id' => $this->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' => $v->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' => $v->id]); if ($v->pay_type == 2) { $v->is_pay = 1; $v->save(); } } } /** * 自动取消认养配送订单 */ public function adoptCostOrderCancel() { $time = time(); $over_time = Option::get(OptionSetting::STORE_DELIVERY_TIME, $this->store_id)['value']; if (!$over_time) { $over_time = 1; } $over_day = $time - ($over_time * 86400); $orders = AdoptCostOrder::find()->where(['is_delete' => 0, 'is_pay' => 0, 'store_id' => $this->store_id,]) ->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CANCEL]) ->andWhere(['<=', 'created_at', $over_day])->andWhere(['!=', 'pay_type', 2]) ->all(); /* @var AdoptCostOrder[] $orders */ if (!empty($orders)) { foreach ($orders as $order) { $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' => $this->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(); continue; } $t->commit(); } } } /** * 抖品发放佣金 */ 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()); } } /** * 成为股东自动成为分销商 * @param $user_id integer 用户id */ private function shareHolderAutoBecomeShare() { $share_holder_list = ShareHolder::find()->alias('sh') ->where(['sh.is_delete' => 0, 'sh.status' => 1]) ->leftJoin(['s' => Share::tableName()], 'sh.user_id=s.user_id') ->andWhere('s.id is null') ->select('sh.*') ->asArray()->all(); foreach ($share_holder_list as $k => $v) { $user_id = $v['user_id']; $store_id = $v['store_id']; $share = Share::findOne(['user_id' => $user_id, 'is_delete' => 0, 'store_id' => $store_id]); if ($share && $share->status == 1) { continue; } 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(); } } /** * 用户自动成为分销商 * @param $user_id integer 用户id */ private function userAutoBecomeShare() { $store_id = $this->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; // if (!empty($share_basic_setting['share_condition']) && !empty($share_basic_setting['auto_share_val'])) { //判断无需审核且消费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(['is_delete' => 0, 'store_id' => $store_id, 'status' => 1])->select('user_id') ->column(); //筛出已经被删除的分销商 $filter_delete_user_id = Share::find()->where(['is_delete' => 1, 'store_id' => $store_id, 'status' => 1])->select('user_id') ->column(); $filter_user_id = array_merge($filter_user_id, $filter_delete_user_id); //查询用户 $user_query = User::find()->where(['store_id' => $store_id, 'is_delete' => 0]); if (!empty($filter_user_id)) { $user_query->andWhere(['NOT IN', 'id', $filter_user_id]); } $user_list = $user_query->select('id')->column(); foreach ($user_list as $item) { $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; $share->created_at = time(); } $share->status = 1; $share->store_id = $store_id; if ($share->save()) { $user = User::findOne($item); $user->time = time(); $user->is_distributor = 1; $user->save(); } } } // } } public function seckillActivityOrder($store_id) { try { $activity_order_log = SeckillActivityOrderLog::find()->alias('sao')->where(['AND', [ '<', 'sao.created_at', (time() - (60 * 15)) ], [ 'sao.is_delete' => 0, 'sao.store_id' => $store_id, ]])->andWhere([ 'OR', [ 'o.trade_status' => 1 ], [ 'o.is_pay' => 0, ] ])->leftJoin(['o' => Order::tableName()], 'sao.order_id = o.id')->select('sao.id, sao.is_delete, sao.activity_goods_id, sao.activity_id, sao.num, sao.goods_id')->all(); foreach ($activity_order_log as $item) { $goods = SeckillActivityGoods::findOne(['is_delete' => 0, 'goods_id' => $item->goods_id, 'activity_id' => $item->activity_id]); if ($goods) { $goods->sale_num -= $item->num; if (!$goods->save()) { throw new \Exception(json_encode($goods->errors)); } } $item->is_delete = 1; if (!$item->save()) { throw new \Exception(json_encode($item->errors)); } } } catch (\Exception $e) { \Yii::error("秒杀逻辑处理" . $e->getMessage()); // return [ // 'code' => 1, // 'msg' => $e->getMessage() // ]; } } //拼团 public function ptActivityOrder($store_id) { try { //判断团长下单的人 $pt_order_all = PtActivityOrder::find()->alias('o') ->where(['o.store_id' => $store_id, 'o.is_pay' => 1, 'o.trade_status' => 0, 'is_pt_finish' => 0]) ->leftJoin(['od' => PtActivityOrderDetail::tableName()], 'o.id = od.order_id') ->andWhere(['o.pt_number' => 0])->select('o.id, od.activity_id, o.pay_time')->asArray()->all(); foreach ($pt_order_all as $pt_order) { $activity = PtActivity::findOne($pt_order['activity_id']); $split_time = ($activity->split_time * 60 * 60); //已经过期,需要失败处理 if ((time() - $split_time > $pt_order['pay_time']) || $activity->end_time < time()) { $pt_order_ = PtActivityOrder::find()->where(['is_pay' => 1]) ->andWhere(['OR', ['id' => $pt_order['id']], ['pt_number' => $pt_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($pt_order['id']); if ($result['code'] !== 0) { throw new \Exception($result['msg']); } } } } catch (\Exception $e) { \Yii::error("拼团逻辑处理" . $e->getMessage()); // return [ // 'code' => 1, // 'msg' => $e->getMessage() // ]; } } private function agencyPrice($order_id){ try { $order = Order::findOne($order_id); $option = Option::get('agency_price_config', 0, 'saas', [])['value']; debug_log('agency_price_config' . $option); if ($option) { $option = json_decode($option, true); } $province_percent = $option['province_percent'] ?? 0; $city_percent = $option['city_percent'] ?? 0; $district_percent = $option['district_percent'] ?? 0; $bdoption = Option::get('bd_agency_price_config', 0, 'saas', [])['value']; debug_log('bd_agency_price_config' . $bdoption); if ($bdoption) { $bdoption = json_decode($bdoption, true); } $bd_agent_percent = $bdoption['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; } //给用户增加佣金 $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); } } } } catch (\Exception $e) { \Yii::error($e->getMessage()); } } private function sendGoodsAgentMoney($order_id){ $t = \Yii::$app->db->beginTransaction(); try { $order = Order::findOne($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')->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'])) { //抓取云仓佣金 $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); //给用户增加佣金 $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); //给用户增加佣金 $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()); } } /** * 同城配送订单处理 */ private function localDeliveryOrder() { \Yii::warning(['---- Order Event BEGIN 自动派单发放开始 localDeliveryOrder ----']); $time = time(); $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; } if ($local_setting['send_type']['value'] != 'auto') { //未开启自动派单 \Yii::warning(['---- Order Event BEGIN 平台未开启自动派单 localDeliveryOrder ----']); return false; } $default_time = $local_setting['default_time']['value']; //默认预计送达所消耗的时间,例:30分钟 //待分配骑手的订单 $list = Order::find()->alias('o') ->leftJoin(['di' => DeliveryInfo::tableName()], 'o.order_no = di.order_no') ->where(['o.order_type' => Order::ORDER_TYPE_STORE, 'di.is_local' => 1]) ->andWhere([ 'o.trade_status' => Order::ORDER_FLOW_NO_SEND, 'o.is_delete' => Order::IS_DELETE_FALSE, 'di.local_status' => DeliveryInfo::LOCAL_STATUS_NO_SEND, 'di.rider_id' => 0, ]) ->andWhere([ 'or', ['o.is_pay' => Order::IS_PAY_TRUE], ['o.pay_type' => Order::PAY_TYPE_COD] ]) ->andWhere([ 'or', ['<=', 'o.delivery_time', bcadd($time, bcmul($default_time, 60, 0), 0)], ['o.delivery_time' => 0] ]) ->select('o.*') ->all(); foreach ($list as $order) { $this->autoSendDeliveryOrder($order); } } /** * 模块名:autoSendDeliveryOrder * 代码描述:平台自配的同城订单自动派单 * 作者:WPing丶 * 请求方式:GET * 创建时间:2023/07/04 16:39:37 * @param object order */ private function autoSendDeliveryOrder($order) { \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; } $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([ 'or', ['store_id' => $order->store_id], ['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(); //事务执行 } //会员到期 public function userLevelExpiresHandle() { try { //获取已经到期的用户且排除永久日期的用户 $time = time(); $user_list = User::find()->where(['is_delete' => User::USER_NOT_DELETE]) ->andWhere(['AND', ['<', 'user_level_expires', $time], ['>', 'user_level_expires', 0]]) ->asArray()->all(); foreach ($user_list as $user_item) { $user_level_expires_ext = json_decode($user_item['user_level_expires_ext'], true); //排序 $last_names = array_column($user_level_expires_ext, 'level'); array_multisort($last_names, SORT_DESC, $user_level_expires_ext); //去除已经过期的 if ($user_level_expires_ext) { foreach ($user_level_expires_ext as $user_level_index => $user_level_item) { // 去除已经过期的 if ($user_level_item['expires_in'] > 0 && $user_level_item['expires_in'] <= time()) { unset($user_level_expires_ext[$user_level_index]); } } } $user_level_expires_ext = array_values($user_level_expires_ext); $user = User::findOne($user_item['id']); // $user_level_expires = $user->user_level_expires; $user_level = -1; if (isset($user_level_expires_ext[0]['expires_in'])) { $user_level_expires = $user_level_expires_ext[0]['expires_in']; $user_level = $user_level_expires_ext[0]['level']; } $user->user_level_expires_ext = json_encode($user_level_expires_ext, JSON_UNESCAPED_UNICODE); $user->user_level_expires = $user_level_expires; $user->level = $user_level; $user->save(); } $team_grades_list = TeamGrades::find()->where(['is_delete' => User::USER_NOT_DELETE]) ->andWhere(['AND', ['<', 'level_expires', $time], ['>', 'level_expires', 0]]) ->asArray()->all(); foreach ($team_grades_list as $team_grades_item) { $level_expires_ext = json_decode($team_grades_item['level_expires_ext'], true); //排序 $last_names = array_column($level_expires_ext, 'level'); array_multisort($last_names, SORT_DESC, $level_expires_ext); //去除已经过期的 if ($level_expires_ext) { foreach ($level_expires_ext as $user_level_index => $user_level_item) { // 去除已经过期的 if ($user_level_item['expires_in'] > 0 && $user_level_item['expires_in'] <= time()) { unset($level_expires_ext[$user_level_index]); } } } $level_expires_ext = array_values($level_expires_ext); $teamGrades = TeamGrades::findOne($team_grades_item['id']); // $level_expires = 0; $team_grades_level = -1; if (isset($level_expires_ext[0]['expires_in'])) { $level_expires = $level_expires_ext[0]['expires_in']; $team_grades_level = $level_expires_ext[0]['level']; } $teamGrades->level_expires_ext = json_encode($level_expires_ext, JSON_UNESCAPED_UNICODE); $teamGrades->level_expires = $level_expires; $teamGrades->team_grades_level = $team_grades_level; $teamGrades->save(); } } catch (\Exception $e) { } } public function getWechatConfig($store_id) { // TODO: 小程序为例 // 获取微信配置进行初始化 $wechat_config = WechatConfig::findOne(['store_id' => $store_id, 'type' => 1]); if (\Yii::$app->prod_is_dandianpu()) { $platform_mch_appid = Option::get('one_store_wechat_appid', 0, 'saas')['value']; $platform_mch_key = Option::get('one_store_wechat_secret', 0, 'saas')['value']; $wechat_config = (object)[ 'app_id' => $platform_mch_appid, 'app_secret' => $platform_mch_key ]; //没有进件走平台账号 if($store_id > 0){ $hasIncoming = \app\models\Store::hasIncoming($store_id); if(!$hasIncoming){ $mch_id = Option::get('one_store_mch_id', 0, 'saas', '')['value']; $pay_key = Option::get('one_store_pay_key', 0, 'saas', '')['value']; $apiclient_cert = Option::get('one_store_apiclient_cert', 0, 'saas', '')['value']; $apiclient_key = Option::get('one_store_apiclient_key', 0, 'saas', '')['value']; $wechat_config->mch_id = $mch_id; $wechat_config->pay_key = $pay_key; $wechat_config->cert_pem = $apiclient_cert; $wechat_config->key_pem = $apiclient_key; } } } else { //如果是商盟 获取商盟小程序配置信息 if($store_id == -1){ $keys = [ 'platform_appid', 'platform_mch_id', 'platform_key', 'platform_apiclient_cert', 'platform_apiclient_key', 'platform_pay_key', ]; $data = Option::get($keys, 0, 'saas'); if (empty($data)) { $data = [ 'platform_appid' => '', 'platform_mch_id' => '', 'platform_key' => ' ', 'platform_apiclient_cert' => '', 'platform_apiclient_key' => '', 'platform_pay_key'=> '', ]; } else { $arr = []; foreach ($data as $value) { $index = array_search($value['name'], $keys); unset($keys[$index]); $arr[$value['name']] = $value['value']; } foreach ($keys as $key) { $arr[$key] = ''; } $data = $arr; } $wechat_config =new WechatConfig(); $wechat_config->app_id = $data['platform_appid']; $wechat_config->app_secret = $data['platform_key']; $wechat_config->mch_id = $data['platform_mch_id']; $wechat_config->pay_key = $data['platform_pay_key']; $wechat_config->cert_pem = $data['platform_apiclient_cert']; $wechat_config->key_pem = $data['platform_apiclient_key']; } } // 证书 if (!is_dir(\Yii::$app->runtimePath . '/pem')) { mkdir(\Yii::$app->runtimePath . '/pem'); file_put_contents(\Yii::$app->runtimePath . '/pem/index.html', ''); } $cert_pem_file = null; if (isset($wechat_config->cert_pem) && $wechat_config->cert_pem) { $cert_pem_file = \Yii::$app->runtimePath . '/pem/' . md5($wechat_config->cert_pem); if (!file_exists($cert_pem_file)) { file_put_contents($cert_pem_file, $wechat_config->cert_pem); } } $key_pem_file = null; if (isset($wechat_config->key_pem) && $wechat_config->key_pem) { $key_pem_file = \Yii::$app->runtimePath . '/pem/' . md5($wechat_config->key_pem); if (!file_exists($key_pem_file)) { file_put_contents($key_pem_file, $wechat_config->key_pem); } } $config = [ 'app_id' => $wechat_config->app_id, 'secret' => $wechat_config->app_secret, 'key' => $wechat_config->pay_key ?? '', 'mch_id' => $wechat_config->mch_id ?? '', 'cert_path' => $cert_pem_file, 'key_path' => $key_pem_file, 'response_type' => 'array' ]; return Factory::payment($config); } //获取微信转账状态 public function getWechatCashStatus($store_id) { $cash_list = Cash::find()->where( [ 'store_id' => $store_id, 'is_delete' => 0, 'status' => Cash::STATUS_GIVEN, 'pay_type' => Cash::PAY_TYPE_WX, 'wx_cash_status' => [ -1, Cash::WX_CASH_STATUS_INIT, Cash::WX_CASH_STATUS_WAIT_PAY, Cash::WX_CASH_STATUS_PROCESSING ], 'wx_cash_type' => Cash::WX_CASH_TYPE_OLD ])->asArray()->all(); $wechat = $this->getWechatConfig($store_id); $Wxv3 = (new \app\utils\WechatMerchant\WxV3($wechat)); foreach ($cash_list as $item) { $this->handleWechatCashFail($Wxv3, $store_id, $item['order_no']); } } public static function handleWechatCashFail($Wxv3, $store_id, $order_no) { $cash = Cash::findOne(['order_no' => $order_no, 'is_delete' => 0, 'wx_cash_status' => [ -1, Cash::WX_CASH_STATUS_INIT, Cash::WX_CASH_STATUS_WAIT_PAY, Cash::WX_CASH_STATUS_PROCESSING ], 'wx_cash_type' => Cash::WX_CASH_TYPE_OLD]); if ($cash) { $result = $Wxv3->getBatchDetail($store_id, ['out_batch_no' => $order_no]); if (!$result['code']) { $cash->wx_cash_status = Cash::WX_CASH_STATUS_ARR[$result['data']['detail_status']]; $cash->wx_cash_error = ""; if (intval($cash->wx_cash_status) === Cash::WX_CASH_STATUS_FAIL) { $cash->wx_cash_error = Cash::WX_CASH_FAIL_REASON[$result['data']['fail_reason']]; $cash->status = Cash::STATUS_REFUSE; cash::cashRefuse($cash->id); } if ($cash->save()) { $user = User::findOne(['id' => $cash->user_id]); debug_log([ 'type' => '提现驳回成功', 'result' => $result ], 'wechat_cash_status.log'); NoticeSend::CashFail($cash->user_id, $user->binding, $cash->price, '提现被驳回', '提现被驳回', $store_id); } else { debug_log([ 'type' => '提现驳回失败', 'error' => json_encode($cash->errors, JSON_UNESCAPED_UNICODE) ], 'wechat_cash_status.log'); } } } } }