- Go to script.google.com → New project
- Paste the Apps Script code below, save
- Deploy → New deployment → Web app
Execute as: Me · Access: Anyone
- Copy the deployment URL and paste it here
Apps Script code
const SHEET_NAME = 'Sessions';
function doPost(e) {
try {
const d = JSON.parse(e.postData.contents);
const s = getSheet();
if (d.action === 'start') {
s.appendRow([d.rowId,d.date,d.weekday,d.start,
'','',d.type,'','','','active','',
d.created_at,d.created_at]);
} else {
updateRow(s, d);
}
return json({ok:true});
} catch(e) { return json({ok:false,error:e.toString()}); }
}
function doGet(e) {
try {
if (e.parameter.action==='get') {
const s = getSheet();
const rows = s.getDataRange().getValues();
for (let i=rows.length-1;i>=1;i--) {
if (rows[i][1]===e.parameter.date
&& rows[i][10]==='active') {
return json({rowId:rows[i][0],
date:rows[i][1],start:rows[i][3],
type:rows[i][6],status:'active'});
}
}
}
return json(null);
} catch(e) { return json(null); }
}
function updateRow(s, d) {
const rows = s.getDataRange().getValues();
for (let i=1;i<rows.length;i++) {
if (rows[i][0]!==d.rowId) continue;
const r = i+1;
if (d.action==='stop') {
s.getRange(r,5).setValue(d.end||'');
s.getRange(r,6).setValue(d.duration||'');
s.getRange(r,8).setValue(d.mood||'');
s.getRange(r,9).setValue(d.last_food||'');
s.getRange(r,10).setValue(d.comment||'');
s.getRange(r,11).setValue('done');
s.getRange(r,12).setValue(d.heartbeat_elapsed||'');
s.getRange(r,14).setValue(d.updated_at||'');
} else if (d.action==='heartbeat') {
s.getRange(r,12).setValue(d.heartbeat_elapsed||'');
s.getRange(r,14).setValue(d.updated_at||'');
} else if (d.action==='discard') {
s.getRange(r,11).setValue('cancelled');
s.getRange(r,14).setValue(d.updated_at||'');
}
return;
}
}
function getSheet() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
let s = ss.getSheetByName(SHEET_NAME);
if (!s) {
s = ss.insertSheet(SHEET_NAME);
s.appendRow(['rowId','date','weekday','start',
'end','duration','type','mood','last_food',
'comment','status','heartbeat_elapsed',
'created_at','updated_at']);
}
return s;
}
function json(d) {
return ContentService
.createTextOutput(JSON.stringify(d))
.setMimeType(ContentService.MimeType.JSON);
}