Scheduling infrastructure for absolutely everyone.
fix: zero-pad username suggestion suffix consistently (#29571)
Yash Singh1599dfd5158b
diff --git a/packages/lib/server/username.test.ts b/packages/lib/server/username.test.tsindex 3d3b653a8c7..87ec703fa91 100644--- a/packages/lib/server/username.test.ts+++ b/packages/lib/server/username.test.ts@@ -1,8 +1,8 @@import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";-import { describe, expect, it, beforeEach } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { usernameCheckForSignup } from "./username";+import { generateUsernameSuggestion, usernameCheckForSignup } from "./username";describe("usernameCheckForSignup ", async () => {beforeEach(() => {@@ -57,6 +57,33 @@ describe("usernameCheckForSignup ", async () => {});});+describe("generateUsernameSuggestion", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("appends a zero-padded suffix when the username is free on the first attempt", async () => {+ const suggestion = await generateUsernameSuggestion([], "john");+ expect(suggestion).toBe("john001");+ });++ it("zero-pads a two-digit suffix to a consistent width", async () => {+ // Force the first candidate (john001) to collide so a random suffix is generated,+ // and pin Math.random so the generated suffix is the two-digit number 42.+ // username length >= 2 -> limit 999 -> rand = ceil(1 + random * 998); 40.5/998 -> ceil(41.5) = 42.+ vi.spyOn(Math, "random").mockReturnValue(40.5 / 998);+ const suggestion = await generateUsernameSuggestion(["john001"], "john");+ expect(suggestion).toBe("john042");+ });++ it("zero-pads a three-digit suffix to a consistent width", async () => {+ // 122.5/998 -> ceil(1 + 122.5) = ceil(123.5) = 124.+ vi.spyOn(Math, "random").mockReturnValue(122.5 / 998);+ const suggestion = await generateUsernameSuggestion(["john001"], "john");+ expect(suggestion).toBe("john124");+ });+});+function mockUserInDB({ id, email, username }: { id: number; email: string; username: string }) {// @ts-expect-errorprismaMock.user.findUnique.mockImplementation((arg) => {diff --git a/packages/lib/server/username.ts b/packages/lib/server/username.tsindex 9b3cfc16fee..7ad801fdf6e 100644--- a/packages/lib/server/username.ts+++ b/packages/lib/server/username.ts@@ -57,11 +57,12 @@ export const isPremiumUserName = IS_PREMIUM_USERNAME_ENABLEDexport const generateUsernameSuggestion = async (users: string[], username: string) => {const limit = username.length < 2 ? 9999 : 999;+ const suffix = (value: number) => String(value).padStart(3, "0");let rand = 1;- while (users.includes(username + String(rand).padStart(4 - rand.toString().length, "0"))) {+ while (users.includes(username + suffix(rand))) {rand = Math.ceil(1 + Math.random() * (limit - 1));}- return username + String(rand).padStart(4 - rand.toString().length, "0");+ return username + suffix(rand);};const processResult = (