factory_id > 0) { return self::get($user->factory_id); } $inviteCode = strtoupper(trim((string)$inviteCode)); if ($inviteCode !== '') { return self::joinByInvite($user, $inviteCode); } $factoryCfg = \think\Config::get('ps.factory'); $autoCreate = true; if (is_array($factoryCfg) && array_key_exists('register_create_factory', $factoryCfg)) { $autoCreate = (bool)$factoryCfg['register_create_factory']; } if (!$autoCreate) { return null; } return self::createForOwner($user, $factoryName); } /** * 为新注册用户创建工厂并设为管理员 * @param User $user * @param string $factoryName * @return Factory * @throws Exception */ public static function createForOwner(User $user, $factoryName = '') { $name = trim((string)$factoryName); if ($name === '') { throw new Exception('请填写工厂名称'); } if (mb_strlen($name) > 100) { throw new Exception('工厂名称不能超过100个字'); } $scoreCfg = \think\Config::get('ps.score') ?: []; $gift = isset($scoreCfg['register_gift']) ? (int)$scoreCfg['register_gift'] : 0; if ($gift < 0) { $gift = 0; } $factory = self::create([ 'name' => $name, 'code' => 'F' . date('ymd') . $user->id, 'invite_code' => self::uniqueInviteCode(), 'owner_user_id' => $user->id, 'score' => $gift, 'status' => 'normal', ]); $user->save([ 'factory_id' => $factory->id, 'factory_role' => 'owner', ]); return $factory; } /** * 凭邀请码加入工厂(操作员) * @param User $user * @param string $inviteCode * @return Factory * @throws Exception */ public static function joinByInvite(User $user, $inviteCode) { $factory = self::where('invite_code', strtoupper(trim($inviteCode))) ->where('status', 'normal') ->find(); if (!$factory) { throw new Exception('邀请码无效'); } $user->save([ 'factory_id' => $factory->id, 'factory_role' => 'operator', ]); return $factory; } /** * 变更工厂积分(行锁) * @param int $factoryId * @param int $score 正加负减 * @param string $bizType * @param int $bizId * @param string $memo * @param int $operatorUserId * @return Factory * @throws Exception */ public static function changeScore($factoryId, $score, $bizType, $bizId, $memo, $operatorUserId = 0) { if ((int)$score === 0) { return self::get($factoryId); } Db::startTrans(); try { $factory = self::lock(true)->find($factoryId); if (!$factory) { throw new Exception('工厂不存在'); } $before = (int)$factory->score; $after = $before + (int)$score; if ($after < 0) { throw new Exception('工厂积分不足'); } $factory->save(['score' => $after]); FactoryScoreLog::create([ 'factory_id' => $factoryId, 'operator_user_id' => $operatorUserId, 'score' => $score, 'before' => $before, 'after' => $after, 'biz_type' => $bizType, 'biz_id' => $bizId, 'memo' => $memo, ]); Db::commit(); return $factory; } catch (\Exception $e) { Db::rollback(); throw $e; } } protected static function uniqueInviteCode() { do { $code = strtoupper(Random::alnum(8)); } while (self::where('invite_code', $code)->find()); return $code; } }