Add auto-generated account numbers and member numbers
6-digit random numbers generated on create, unique per company. Member number column added to member table. Both displayed in UI tables.
This commit is contained in:
@@ -26,12 +26,35 @@ import {
|
||||
paginatedResponse,
|
||||
} from '../utils/pagination.js'
|
||||
|
||||
async function generateUniqueNumber(
|
||||
db: PostgresJsDatabase,
|
||||
table: typeof accounts | typeof members,
|
||||
column: typeof accounts.accountNumber | typeof members.memberNumber,
|
||||
companyId: string,
|
||||
companyIdColumn: typeof accounts.companyId,
|
||||
): Promise<string> {
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
const num = String(Math.floor(100000 + Math.random() * 900000))
|
||||
const [existing] = await db
|
||||
.select({ id: table.id })
|
||||
.from(table)
|
||||
.where(and(eq(companyIdColumn, companyId), eq(column, num)))
|
||||
.limit(1)
|
||||
if (!existing) return num
|
||||
}
|
||||
// Fallback to 8 digits if 6-digit space is crowded
|
||||
return String(Math.floor(10000000 + Math.random() * 90000000))
|
||||
}
|
||||
|
||||
export const AccountService = {
|
||||
async create(db: PostgresJsDatabase, companyId: string, input: AccountCreateInput) {
|
||||
const accountNumber = await generateUniqueNumber(db, accounts, accounts.accountNumber, companyId, accounts.companyId)
|
||||
|
||||
const [account] = await db
|
||||
.insert(accounts)
|
||||
.values({
|
||||
companyId,
|
||||
accountNumber,
|
||||
name: input.name,
|
||||
email: input.email,
|
||||
phone: input.phone,
|
||||
@@ -137,11 +160,13 @@ export const MemberService = {
|
||||
) {
|
||||
// isMinor: explicit flag wins, else derive from DOB, else false
|
||||
const minor = input.isMinor ?? (input.dateOfBirth ? isMinor(input.dateOfBirth) : false)
|
||||
const memberNumber = await generateUniqueNumber(db, members, members.memberNumber, companyId, members.companyId)
|
||||
|
||||
const [member] = await db
|
||||
.insert(members)
|
||||
.values({
|
||||
companyId,
|
||||
memberNumber,
|
||||
accountId: input.accountId,
|
||||
firstName: input.firstName,
|
||||
lastName: input.lastName,
|
||||
|
||||
Reference in New Issue
Block a user