public function pay($total_fee, $transaction = TRUE) { $transaction && DB::beginTransaction(); $order = static::where($this->getKeyName(), $this->getKey())->lockForUpdate()->first(); if ($order->status != static::INIT) { $transaction && DB::rollback(); return false; } //对账失败 if (abs($total_fee - $order->total_money * 100) >= 0.01) { $order->status = static::COMPARE_BILL_FAIL; $order->save(); $transaction && DB::commit(); return false; } //用户已消费 $order->bills()->create(['value' => -$order->total_money, 'uid' => $order->uid, 'event' => Bill::PURCHASE]); //一个订单里面只能有一个厂家的details $details = $order->details; $total = $details->sum('money'); $factory_money = $order->total_money; $store_money = $agent_money = []; $user_stores = User::find($order->uid)->stores()->get(['stores.id']); //关注的店铺 foreach ($details as $detail) { $rate = $order->details_money * $detail->money / $total; $brand = $detail->product->brand; $store = Store::whereIn('stores.id', $user_stores->pluck('id')->toArray())->join('store_brand', 'store_brand.sid', '=', 'stores.id')->where('store_brand.bid', $brand->getKey())->first(['stores.*']); if (!empty($store)) { !isset($store_money[$store->getKey()]) && ($store_money[$store->getKey()] = 0); $store_money[$store->getKey()] += $value = $rate * $detail->product->shop_rate / 100; $factory_money -= $value; $agent = Agent::whereIn('agents.id', $store->agent_ids()->toArray())->join('agent_brand', 'agent_brand.aid', '=', 'agents.id')->where('agent_brand.bid', $brand->getKey())->first(['agents.*']); if (!empty($agent)) { !isset($agent_money[$agent->getKey()]) && ($agent_money[$agent->getKey()] = 0); $agent_money[$agent->getKey()] += $value = $rate * $detail->product->agent_rate / 100; $factory_money -= $value; } } } if (!empty($details)) { //门店提成 foreach ($store_money as $uid => $value) { $order->bills()->create(['value' => $value, 'uid' => $uid, 'event' => Bill::COMMISSION]); } //代理商提成 foreach ($agent_money as $uid => $value) { $order->bills()->create(['value' => $value, 'uid' => $uid, 'event' => Bill::COMMISSION]); } //厂商收入 $order->bills()->create(['value' => $factory_money < 0 ? 0 : $factory_money, 'uid' => $details[0]->product->fid, 'event' => Bill::INCOME]); } $order->status = static::PAID; $order->save(); if (intval($order->bonus_id) > 0) { $bonus = ActivityBonus::where('id', $order->bonus_id)->lockForUpdate()->first(); $bonus->status = 2; //已使用红包 $bonus->save(); } $transaction && DB::commit(); return true; }