MC/website/node/personnel-numbers.mjs
2026-11-27 23:43:05 +00:00

20 lines
2.5 KiB
JavaScript

export const DIRECTORY_OWNER_ID='f3ffda37-01e4-41ea-b89d-fbeda82e453e';
export const personnelSchema=[
`CREATE TABLE IF NOT EXISTS directory_number_sequence (sequence_key VARCHAR(24) PRIMARY KEY,next_number INT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS directory_personnel (user_id CHAR(36) PRIMARY KEY,personnel_number INT NOT NULL UNIQUE,assigned_by CHAR(36) NOT NULL,assigned_at BIGINT NOT NULL,FOREIGN KEY(user_id) REFERENCES site_accounts(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
];
export const personnelLabel=number=>Number.isSafeInteger(Number(number))&&Number(number)>0?'DR-'+String(number).padStart(4,'0'):null;
// Caller owns the account/appointment transaction. Numbers are permanent and do
// not grant access. 0001 remains reserved for the verified primary owner.
export async function ensurePersonnelNumber(tx,userId,{actorId=DIRECTORY_OWNER_ID,now=Date.now()}={}){
await tx.query("INSERT INTO directory_number_sequence(sequence_key,next_number) VALUES('people',2) ON DUPLICATE KEY UPDATE sequence_key=VALUES(sequence_key)");
const counter=await tx.first("SELECT next_number FROM directory_number_sequence WHERE sequence_key='people' FOR UPDATE");
const existing=await tx.first('SELECT personnel_number FROM directory_personnel WHERE user_id=? FOR UPDATE',[userId]);if(existing)return personnelLabel(existing.personnel_number);
const target=await tx.first("SELECT a.id,a.username,a.role,a.password_hash,p.game_link_exempt FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.id=? FOR SHARE",[userId]);
if(!target||target.role==='official_account'||Number(target.game_link_exempt)||String(target.password_hash).startsWith('!'))return null;
let number=Number(counter.next_number);
if(userId===DIRECTORY_OWNER_ID){if(target.username!=='unimatrix999')throw Error('Primary owner identity requires review.');number=1;}
else{if(!Number.isSafeInteger(number)||number<2||number>99999999)throw Error('Directory number sequence requires review.');await tx.query("UPDATE directory_number_sequence SET next_number=? WHERE sequence_key='people'",[number+1]);}
await tx.query('INSERT INTO directory_personnel(user_id,personnel_number,assigned_by,assigned_at) VALUES(?,?,?,?)',[userId,number,actorId,now]);return personnelLabel(number);
}
export async function personnelNumberFor(db,userId){const row=await db.prepare('SELECT personnel_number FROM directory_personnel WHERE user_id=?').bind(userId).first();return personnelLabel(row?.personnel_number);}