update(['user_id' => $to]); Message::where('user_id', $from)->update(['user_id' => $to]); Message::where('to_user_id', $from)->update(['to_user_id' => $to]); $dialogues = Dialogue::where(function ($q) use ($from) { $q->where('user_id', $from)->orWhere('to_user_id', $from); })->lockForUpdate()->get(); foreach ($dialogues as $d) { $a = (int) $d->user_id === (int) $from ? $to : $d->user_id; $b = (int) $d->to_user_id === (int) $from ? $to : $d->to_user_id; $key = Conversations::key($d->supply_demand_id, $a, $b); $existing = Dialogue::where('conversation_key', $key)->where('id', '!=', $d->id)->lockForUpdate()->first(); if ($existing) { Message::where('dialogue_id', $d->id)->update(['dialogue_id' => $existing->id]); if ($d->last_datetime > $existing->last_datetime) { $existing->last_content = $d->last_content; $existing->last_datetime = $d->last_datetime; $existing->save(); } $d->delete(); } else { $d->user_id = $a; $d->to_user_id = $b; $d->conversation_key = $key; $d->save(); } } Message::where('user_id', $to)->where('to_user_id', $to)->update(['is_read' => 1]); }); } public static function verified(User $user) { $user->supply_mobile_verified_at = now(); $user->save(); return self::autoBind($user); } public static function autoBind(User $user) { $mobile = $user->getRawOriginal('mobile'); if (!$user->supply_mobile_verified_at || !preg_match('/^1\d{10}$/', (string) $mobile)) return 0; if (User::where('mobile', $mobile)->count() !== 1) { SupplyDemand::where('is_proxy', 1)->where('publisher_mobile', $mobile)->where('user_id', 0)->update(['binding_note' => '手机号对应多个学员,请人工核实']); return 0; } $count = 0; foreach (SupplyDemand::where('is_proxy', 1)->where('user_id', 0)->where('publisher_mobile', $mobile)->get() as $d) { self::bind($d, $user); $count++; } return $count; } public static function bind(SupplyDemand $d, User $user) { return DB::transaction(function () use ($d, $user) { $d = SupplyDemand::whereKey($d->id)->lockForUpdate()->firstOrFail(); if (!$d->is_proxy || $d->user_id) throw new \InvalidArgumentException('仅可绑定尚未认领的代发需求'); if (!$user->supply_mobile_verified_at) throw new \InvalidArgumentException('请先让该学员完成手机号验证'); $d->user_id = $user->id; $d->bound_at = now(); $d->binding_note = null; $d->save(); foreach (Dialogue::where('supply_demand_id', $d->id)->where('to_user_id', 0)->lockForUpdate()->get() as $dialogue) { // 本人此前咨询的需求在认领后保留历史,禁止继续向自己发消息。 $dialogue->to_user_id = $user->id; $dialogue->conversation_key = Conversations::key($d->id, $dialogue->user_id, $user->id); $dialogue->save(); } $pending = Message::where('supply_demand_id', $d->id)->where('to_user_id', 0)->where('user_id', '!=', $user->id); $hasPending = (clone $pending)->exists(); $pending->update(['to_user_id' => $user->id, 'is_read' => 0]); Message::where('supply_demand_id', $d->id)->where('to_user_id', 0)->where('user_id', $user->id)->update(['to_user_id' => $user->id, 'is_read' => 1]); if ($hasPending) Notices::queue($user->id); return $d; }); } }