// Apps Script: Unique Number + Wallet + Google sign-in required
const POOL_SHEET_NAME = 'Pool';
const ASSIGNED_SHEET_NAME = 'Assigned';
function doGet(e){
return ContentService.createTextOutput('Random Number Distributor (use POST/GET request).');
}
// Support GET for simplicity
function doGetJSON(e) {
return handleRequest(e.parameter || {});
}
function doPost(e){
// support JSON body
const params = (e.postData && e.postData.type === 'application/json')
? JSON.parse(e.postData.contents)
: (e.parameter || {});
return handleRequest(params);
}
function handleRequest(params){
// expected params: action=claim, clientId, wallet (required)
const action = (params.action || 'claim').toString();
const clientId = (params.clientId || '').toString();
const wallet = (params.wallet || '').toString().trim();
// get caller email (requires deployment that enforces sign-in or at least allow checking)
const callerEmail = getCallerEmail();
if(action !== 'claim'){
return jsonResponse({ ok:false, error:'unknown action' });
}
if(!clientId){
return jsonResponse({ ok:false, error:'missing clientId' });
}
if(!callerEmail){
// no signed-in user detected
return jsonResponse({ ok:false, error:'sign-in-required', msg:'Please sign in with Google to continue.'});
}
if(!wallet){
return jsonResponse({ ok:false, error:'missing_wallet', msg:'Wallet number is required.'});
}
return claimNumberForClient(clientId, callerEmail, wallet);
}
function getCallerEmail(){
// Session.getActiveUser().getEmail() returns the effective user email if app enforces sign-in.
// If empty, we treat as not signed-in/anonymous.
try {
const email = Session.getActiveUser().getEmail();
return email || '';
} catch(e) {
return '';
}
}
function claimNumberForClient(clientId, email, wallet){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const lock = LockService.getScriptLock();
try {
lock.waitLock(5000);
} catch (e){
return jsonResponse({ ok:false, error:'lock_timeout' });
}
try {
const assignedSheet = ss.getSheetByName(ASSIGNED_SHEET_NAME);
const poolSheet = ss.getSheetByName(POOL_SHEET_NAME);
if(!assignedSheet || !poolSheet) return jsonResponse({ ok:false, error:'sheets_not_configured' });
// 1) Check if this clientId already assigned -> return existing (do NOT allow changing wallet)
const assignedRange = assignedSheet.getDataRange();
const assignedVals = assignedRange.getValues(); // includes header
for(let i=1;i keep number, mark col B)
poolSheet.getRange(foundRow, 2).setValue('USED at ' + ts.toISOString());
return jsonResponse({ ok:true, existing:false, record: { clientId: clientId, email: email, wallet: wallet, number: number, timestamp: ts }});
} catch(err){
return jsonResponse({ ok:false, error: err.message });
} finally {
try{ lock.releaseLock(); }catch(e){}
}
}
function jsonResponse(obj){
const out = ContentService.createTextOutput(JSON.stringify(obj));
out.setMimeType(ContentService.MimeType.JSON);
return out;
}
تعليقات
إرسال تعليق