Tips for ' + span + ' are paid on ' + C.d(b.paid, 'long') + ', so they will appear under ' + C.d(b.paid, 'my') + '.
';
}).join('') +
'
These are the total tips received at ' + esc(v.venue) + ' and your own share. We don\'t share other people\'s amounts.
' +
'
' + esc(v.contact) + '
';
}
/* ---------- policy (5.9, s27I) ---------- */
var ASK = { no: 'No. Tips are up to the customer.', encourage: 'We encourage customers to tip, but it is always up to them.', service: 'We add a service charge to the bill. Customers can ask us to remove it.' };
var METHOD_WORDS = { 'Equal': 'equally', 'Hours': 'by hours worked', 'Points': 'by points', 'Hours \u00d7 points': 'by hours worked times points' };
function ruleWords(o, pointsMean) {
var pts = '';
var s = o.groupsOn ? o.groups.map(function (g, i) {
return (i ? g.name + ' staff share ' + num(g.pct) + '% ' : g.name + ' staff share ' + num(g.pct) + '% of tips ') + METHOD_WORDS[g.method] + '.';
}).join(' ') : 'Tips are shared between all staff ' + METHOD_WORDS[o.method] + '.';
var usesPoints = (o.groupsOn ? o.groups.map(function (g) { return g.method; }) : [o.method]).some(function (m) { return /Points|points/.test(m); });
if (usesPoints && pointsMean) pts = ' Points stand for ' + pointsMean.replace(/\.$/, '') + '.';
return s + pts + (o.pool === 'day' ? ' Tips are shared day by day, among the staff who worked that day.' : '');
}
// a = form answers: {ask, ways:[...], who, when, consultOn, consultHow, said, contact, pointsMean, today}
function policy(o, a, v) {
var ways = (a.ways && a.ways.length ? a.ways : ['Card', 'Cash']).map(function (x) { return x.toLowerCase(); });
var waysTxt = ways.length > 1 ? ways.slice(0, -1).join(', ') + ' or ' + ways[ways.length - 1] : ways[0];
var S = [
['What counts as a tip here', 'Any tip, gratuity or service charge a customer pays by ' + waysTxt + '.'],
['Do we ask customers to tip?', ASK[a.ask] || ASK.no],
['Who shares', a.who + '.'],
['How shares are worked out', ruleWords(o, a.pointsMean)],
['When tips are paid', a.when + '.'],
['Card fees', '100% of tips go to staff. We keep nothing for card fees.']
];
if (o.tronc > 0 || a.tronc) S.push(['Tronc', 'Part of the tips is paid through a tronc operator, who decides how that part is shared.']);
S.push(['Your records', 'You can ask ' + a.contact + ' for the records of your tips. We\'ll reply within 4 weeks.']);
S.push(['How we asked staff', 'We asked staff for their views by ' + (a.consultHow || 'Meeting').toLowerCase() + ' on ' + C.d(a.consultOn, 'long') + '. What staff said: ' + (a.said || 'no comments.')]);
S.push(['Dates', 'This policy: ' + C.d(a.today, 'long') + '. Review due by ' + C.d(C.addYears(a.today, 3), 'long') + '.']);
S.push(['Who to ask', a.contact]);
return '
How we share tips at ' + esc(v.venue) + '
' +
S.map(function (x) { return '
' + esc(x[0]) + '
' + esc(x[1]) + '
'; }).join('') +
'
Made with Tip Fair. This is a template to help you write your own policy, not legal advice.
';
}
/* ---------- notice (5.10, Ireland) ---------- */
var LAW = 'The law requires that tips and gratuities paid by card or other electronic means are distributed to employees.';
// a = {card: true|false, how, pct, service: true|false, cash}
function noticeLines(a) {
var L = [];
if (a.card) L.push('We share ' + (a.pct || '100%') + ' of card tips with our staff, ' + a.how.charAt(0).toLowerCase() + a.how.slice(1) + '.');
else L.push('We don\'t take tips by card.');
L.push(a.cash === 'Shared the same way' ? 'Cash tips are shared the same way.' : 'Cash tips are kept by the person who receives them.');
L.push(a.service ? 'Our service charge is shared with staff in the same way as card tips.' : 'We don\'t add a service charge.');
return L;
}
function notice(a, v) {
var L = noticeLines(a);
function page(cls) {
return '
' + esc(v.venue) + '
Tips and gratuities
' +
'
' + esc(L[0]) + '
' + L.slice(1).map(function (x) { return '
' + esc(x) + '
'; }).join('') +
'
' + esc(LAW) + '
';
}
return page('tf-a4') + page('tf-a5');
}
function noticeText(a, v) { return v.venue + ': tips and gratuities\n\n' + noticeLines(a).join('\n') + '\n\n' + LAW; }
return { esc: esc, checks: checks, savedLine: savedLine, how: how, statement: statement, statements: statements, letter: letter,
ruleWords: ruleWords, policy: policy, notice: notice, noticeText: noticeText, LAW: LAW };
})();
/**
* Tip Fair: shares tips fairly and keeps the records the tips laws ask for.
* Sheets: Staff, Tips, Hours, Record (+ Shares when written). Settings, mappings and the licence in Document Properties.
* The maths is in core.js, the documents in docs.js. Nothing here sends data out of the spreadsheet.
*/
function onOpen(e) {
SpreadsheetApp.getUi().createAddonMenu().addItem('Open Tip Fair', 'showSidebar').addToUi();
}
function onInstall(e) { onOpen(e); }
function showSidebar() {
SpreadsheetApp.getUi().showSidebar(HtmlService.createTemplate(HTML_FILES_['Sidebar']).evaluate().setTitle('Tip Fair'));
}
function include(name) { return HTML_FILES_[name]; }
function today_() { return Utilities.formatDate(new Date(), ss_().getSpreadsheetTimeZone() || 'Europe/London', 'yyyy-MM-dd'); }
function now_() { return Utilities.formatDate(new Date(), ss_().getSpreadsheetTimeZone() || 'Europe/London', "yyyy-MM-dd HH:mm"); }
function pro_() { return licenceState_(today_()).pro; }
/** 5.1 */
function setup(country, venue) {
if (['GB', 'NI', 'IE'].indexOf(country) < 0) throw new Error('Choose where the venue is.');
saveSettings_({ country: country, venue: String(venue || '').trim().slice(0, 120) || 'My venue' });
setupSheets_(country);
return getState();
}
function saveSettings(patch) {
var keep = {};
['venue', 'country', 'contact'].forEach(function (k) { if (patch[k] != null) keep[k] = String(patch[k]).trim().slice(0, 120); });
if (keep.country && ['GB', 'NI', 'IE'].indexOf(keep.country) < 0) delete keep.country;
var s = saveSettings_(keep);
if (keep.country) setNotes_(s.country);
return getState();
}
function openSheet(name) {
var sh = ss_().getSheetByName(name);
if (sh) ss_().setActiveSheet(sh);
}
/** Default period: the month of the latest tip, or last month. Default payout: the 28th of the month after. */
function defaults_(tips, today) {
var last = tips.reduce(function (a, t) { return t.date > a ? t.date : a; }, '');
var ym = last ? last.slice(0, 7) : Core.addMonths(today.slice(0, 7), -1);
return { from: ym + '-01', to: Core.monthEnd(ym + '-01'), payout: Core.addMonths(ym, 1) + '-28' };
}
function groupsFrom_(staff, saved) {
var names = [];
staff.forEach(function (s) { if (names.indexOf(s.group) < 0) names.push(s.group); });
var old = {};
(saved || []).forEach(function (g) { old[g.name] = g; });
if (names.every(function (n) { return old[n]; }) && (saved || []).length === names.length) return saved;
var base = Math.floor(10000 / Math.max(names.length, 1)), extra = 10000 - base * names.length;
return names.map(function (n, i) { return old[n] || { name: n, pct: (base + (i === 0 ? extra : 0)) / 100, method: 'Hours' }; });
}
/** Everything the home screen (5.2) needs. Counts and totals only. */
function getState() {
var s = settings_(), today = today_(), lic = licenceState_(today);
if (!isSetUp_()) return { setUp: false, licence: lic, today: today };
var st = readStaff_(), tp = readTips_(), hr = readHours_();
var d = defaults_(tp.tips, today);
var o = s.work && s.work.from ? s.work : {};
var from = o.from || d.from, to = o.to || d.to;
var tt = Core.tipsTotal(tp.tips, from, to);
var hrs = hr.hours.filter(function (r) { return !r.date || (r.date >= from && r.date <= to); });
var hTotal = hrs.reduce(function (a, r) { return a + r.hours; }, 0);
var id = from + '_' + to, blocks = Core.readRecord(recordValues_());
var fin = blocks.filter(function (b) { return b.id === id && !b.replaced; })[0];
return {
setUp: true, today: today, licence: lic,
settings: { country: s.country, venue: s.venue, contact: s.contact || '' },
staff: st.staff.map(function (x) { return { name: x.name, group: x.group, points: x.points, type: x.type }; }), badPoints: st.badPoints,
tips: { total: tt.total, count: tt.count, bad: tp.bad, latest: d.from },
hours: { total: hTotal, bad: hr.bad },
work: { from: from, to: to, payout: o.payout || d.payout, groupsOn: o.groupsOn != null ? o.groupsOn : groupsFrom_(st.staff, []).length > 1,
groups: groupsFrom_(st.staff, o.groups), method: o.method || 'Hours', pool: o.pool || 'period', tronc: o.tronc || 0 },
finalised: fin ? { at: fin.at, changed: fin.changed } : null,
records: blocks.filter(function (b) { return !b.replaced; }).length
};
}
/** 5.4 */
function checkHours(from, to) {
var st = readStaff_(), hr = readHours_();
var r = Core.checkHours(st.staff, hr.hours, from, to, Core.d(from, 'm'));
r.bad = hr.bad;
return r;
}
/** 5.3: the sidebar parses the CSV and sends the tips it found. They are checked again here. */
function importTips(tips, mapping) {
var clean = [];
(tips || []).forEach(function (t) {
var date = Core.parseDate(t.date), amount = typeof t.amount === 'number' ? Math.round(t.amount) : Core.parseAmount(t.amount, false);
if (!date || amount == null) return;
clean.push({ date: date, amount: amount, type: Core.TYPES.indexOf(t.type) > -1 ? t.type : 'Card', vat: Math.round(Number(t.vat) || 0),
source: String(t.source || '').slice(0, 60), ref: String(t.ref || '').slice(0, 80) });
});
if (mapping && mapping.key && /^map:/.test(mapping.key)) {
PropertiesService.getDocumentProperties().setProperty(mapping.key, JSON.stringify({ map: mapping.map, source: String(mapping.source || '').slice(0, 60), order: mapping.order || '' }));
}
return appendTips_(clean);
}
function getMapping(key) {
if (!/^map:/.test(key)) return null;
var raw = PropertiesService.getDocumentProperties().getProperty(key);
return raw ? JSON.parse(raw) : null;
}
/** The split settings from the sidebar, kept so the next month starts from them. */
function cleanWork_(w) {
var o = { from: Core.parseDate(w.from), to: Core.parseDate(w.to), payout: Core.parseDate(w.payout), groupsOn: !!w.groupsOn,
method: Core.METHODS.indexOf(w.method) > -1 ? w.method : 'Hours', pool: w.pool === 'day' ? 'day' : 'period', tronc: Math.max(0, Math.round(Number(w.tronc) || 0)),
groups: (w.groups || []).map(function (g) { return { name: String(g.name), pct: Number(g.pct) || 0, method: Core.METHODS.indexOf(g.method) > -1 ? g.method : 'Hours' }; }) };
if (!o.from || !o.to || o.from > o.to) throw new Error('Choose the period again.');
if (!o.payout) throw new Error('Choose the payout date.');
return o;
}
function compute_(w) {
var o = cleanWork_(w), st = readStaff_();
saveSettings_({ work: o });
o.tips = readTips_().tips; o.staff = st.staff; o.hours = readHours_().hours;
return { o: o, r: Core.split(o), staff: st.staff };
}
function view_(o) {
var s = settings_();
return { country: s.country, venue: s.venue, contact: s.contact || '', from: o.from, to: o.to, payout: o.payout, groupsOn: o.groupsOn };
}
/** 5.5 \u2192 5.6. Over 5 people without Pro, only group totals come back (6.10). */
function work(w) {
var c = compute_(w), r = c.r;
if (!r.ok) return { ok: false, error: r.error };
var lock = Core.locked(r, pro_()), v = view_(c.o);
var id = c.o.from + '_' + c.o.to, fin = Core.readRecord(recordValues_()).filter(function (b) { return b.id === id && !b.replaced; })[0];
return {
ok: true, locked: lock, T: r.T, R: r.R, Tsplit: r.Tsplit, byType: r.byType, count: r.count, sharers: r.sharers,
groups: r.groups.map(function (g) {
return { name: g.name, pct: g.pct, method: g.method, pot: g.pot, n: g.people.filter(function (p) { return p.share > 0; }).length,
people: lock ? [] : g.people.map(function (p) { return { name: p.full, h: p.h, p: p.p, share: p.share }; }) };
}),
checks: Docs.checks(r, v, lock), saved: fin ? Docs.savedLine(v) : null, finalisedAt: fin ? fin.at : null
};
}
/** 6.8 */
function finalise(w, note) {
var c = compute_(w), r = c.r;
if (!r.ok) return { ok: false, error: r.error };
if (Core.locked(r, pro_())) return { ok: false, code: 'PRO' };
var rows = Core.recordRows(r, c.o, c.o.payout, now_());
if (note) rows[0][20] = String(note).slice(0, 200);
writeRecord_(rows, c.o.from + '_' + c.o.to, today_());
return { ok: true, saved: Docs.savedLine(view_(c.o)) };
}
function writeShares(w) {
var c = compute_(w), r = c.r;
if (!r.ok) return { ok: false, error: r.error };
if (Core.locked(r, pro_())) return { ok: false, code: 'PRO' };
writeSharesSheet_(r, settings_().venue + ': tip shares, ' + Core.d(c.o.from, 'long') + ' to ' + Core.d(c.o.to, 'long'));
return { ok: true };
}
/** 5.8: finalised periods and the names in them, for the Records screen. */
function getRecords() {
var blocks = Core.readRecord(recordValues_()), names = [];
blocks.forEach(function (b) { if (!b.replaced) b.rows.forEach(function (r) { if (names.indexOf(r[12]) < 0) names.push(r[12]); }); });
return {
blocks: blocks.map(function (b) { return { id: b.id, from: b.from, to: b.to, paid: b.paid, total: b.total, at: b.at, people: b.rows.length, changed: b.changed, replaced: b.replaced, status: b.status }; }).reverse(),
names: names.sort()
};
}
function checkRequest(on, m1, m2) { return Core.requestRange(on, m1, m2); }
/**
* Documents open in a print dialog (7). 'one' is free while the period isn't locked; the rest need Pro (6.10).
* kind: 'one' {w, name} | 'all' {w} | 'letter' {worker, on, m1, m2} | 'policy' {w, a} | 'notice' {a}
*/
function print(kind, x) {
var s = settings_(), html, title;
if (kind !== 'one' && !pro_()) return { ok: false, code: 'PRO' };
if (kind === 'one' || kind === 'all') {
var c = compute_(x.w), r = c.r;
if (!r.ok) return { ok: false, error: r.error };
if (Core.locked(r, pro_())) return { ok: false, code: 'PRO' };
var by = {};
c.staff.forEach(function (p) { by[p.name] = p; });
var only = kind === 'one' ? (r.people.filter(function (p) { return p.full === x.name; })[0] || {}).name : null;
if (kind === 'one' && !only) return { ok: false, error: 'Choose a name from the list.' };
html = Docs.statements(r, view_(c.o), by, only);
title = kind === 'one' ? 'Statement' : 'Statements';
} else if (kind === 'letter') {
var q = Core.requestRange(x.on, x.m1, x.m2);
if (q.errors.length) return { ok: false, error: q.errors[0].text };
var L = Core.letterRows(Core.readRecord(recordValues_()), x.worker, x.m1, x.m2);
html = Docs.letter(L, x, { country: s.country, venue: s.venue, contact: s.contact || '' });
title = 'Reply letter';
} else if (kind === 'policy') {
var o = cleanWork_(x.w);
x.a.today = today_();
html = Docs.policy(o, x.a, { venue: s.venue });
title = 'Tipping policy';
} else if (kind === 'notice') {
html = Docs.notice(x.a, { venue: s.venue });
title = 'Tips notice';
} else throw new Error('Unknown document');
var t = HtmlService.createTemplate(HTML_FILES_['Print']);
t.data = html;
SpreadsheetApp.getUi().showModalDialog(t.evaluate().setWidth(860).setHeight(640), title);
return { ok: true };
}
/** 5.10: the notice as text to copy to a website. */
function noticeText(a) {
if (!pro_()) return { ok: false, code: 'PRO' };
return { ok: true, text: Docs.noticeText(a, { venue: settings_().venue }) };
}
/**
* Tip Fair: reading and writing the sheets. One getValues() and one setValues() per operation.
* Every text value is written through Core.safeText, so a name can't become a formula.
* Logs never hold row data.
*/
var SHEETS = { staff: 'Staff', tips: 'Tips', hours: 'Hours', record: 'Record', shares: 'Shares' };
var HEADERS = {
Staff: ['Name', 'Group', 'Points', 'Type', 'Agency', 'Statement language', 'Notes'],
Tips: ['Date', 'Amount', 'Type', 'VAT part', 'Source', 'Reference'],
Hours: ['Date', 'Name', 'Hours'],
Record: Core.RECORD_COLS,
Shares: ['Name', 'Group', 'Hours', 'Points', 'Share']
};
function ss_() { return SpreadsheetApp.getActiveSpreadsheet(); }
/** Settings live in Document Properties, so they travel with the spreadsheet. */
function settings_() {
var raw = PropertiesService.getDocumentProperties().getProperty('tf');
return raw ? JSON.parse(raw) : {};
}
function saveSettings_(patch) {
var s = settings_();
Object.keys(patch).forEach(function (k) { s[k] = patch[k]; });
PropertiesService.getDocumentProperties().setProperty('tf', JSON.stringify(s));
return s;
}
function isSetUp_() {
var ss = ss_();
return !!settings_().country && ['Staff', 'Tips', 'Hours', 'Record'].every(function (n) { return !!ss.getSheetByName(n); });
}
/** 5.1: adds the four sheets. Safe to run again: sheets that exist keep their data. */
function setupSheets_(country) {
var ss = ss_(), first = null;
['Staff', 'Tips', 'Hours', 'Record'].forEach(function (name) {
var sh = ss.getSheetByName(name);
if (!sh) {
sh = ss.insertSheet(name);
sh.getRange(1, 1, 1, HEADERS[name].length).setValues([HEADERS[name]]).setFontWeight('bold');
sh.setFrozenRows(1);
if (name === 'Record') {
// Plain text, so amounts and dates read back exactly as written and the fingerprint holds.
sh.getRange(1, 1, sh.getMaxRows(), HEADERS.Record.length).setNumberFormat('@');
sh.protect().setWarningOnly(true).setDescription('Written by Tip Fair');
}
if (name === 'Staff') {
sh.getRange(2, 4, 500, 1).setDataValidation(SpreadsheetApp.newDataValidation().requireValueInList(Core.STAFF_TYPES, true).setAllowInvalid(true).build());
sh.getRange(2, 6, 500, 1).setDataValidation(SpreadsheetApp.newDataValidation().requireValueInList(Core.LANGS, true).setAllowInvalid(true).build());
}
if (name === 'Tips') sh.getRange(2, 3, 5000, 1).setDataValidation(SpreadsheetApp.newDataValidation().requireValueInList(Core.TYPES, true).setAllowInvalid(true).build());
if (name === 'Hours') sh.getRange(2, 3, 5000, 1).setNumberFormat('0.00');
if (!first) first = sh;
}
});
setNotes_(country);
if (first) ss.setActiveSheet(ss.getSheetByName('Staff'));
}
/** Header notes (4). They follow the country, so changing it in Settings updates them. */
function setNotes_(country) {
var ss = ss_(), tips = ss.getSheetByName('Tips'), rec = ss.getSheetByName('Record');
if (tips) {
tips.getRange(1, 2).setNote('What the customer paid as a tip, before any card fees. Don\'t take card fees off.');
tips.getRange(1, 4).setNote('Only if this amount includes VAT, such as some service charges. Leave blank otherwise.');
tips.getRange(1, 3).setNote(country === 'IE' ? 'In Ireland a service charge counts as an electronic tip and is shared like one.' : '');
}
if (rec) rec.getRange(1, 1).setNote(country === 'NI' ? 'Written by Tip Fair.' : 'Written by Tip Fair. Keep for 3 years from each payout.');
}
function rows_(name) {
var sh = ss_().getSheetByName(name);
if (!sh) return [];
var n = sh.getLastRow() - 1, c = HEADERS[name].length;
return n > 0 ? sh.getRange(2, 1, n, c).getValues() : [];
}
function str_(v) { return v == null ? '' : String(v).trim(); }
/** Staff, from the Staff sheet. Name is used everywhere, so Hours must match it. */
function readStaff_() {
var out = [], bad = [], seen = {};
rows_('Staff').forEach(function (r) {
var name = str_(r[0]);
if (!name || seen[name]) return;
seen[name] = 1;
var p = Core.parsePoints(r[2]);
if (p == null) { bad.push(name); p = 100; }
var type = str_(r[3]), lang = str_(r[5]);
out.push({ name: name, full: name, group: str_(r[1]) || 'Staff', points: p, type: Core.STAFF_TYPES.indexOf(type) > -1 ? type : 'Worker',
agency: str_(r[4]), lang: Core.LANGS.indexOf(lang) > -1 ? lang : 'English' });
});
return { staff: out, badPoints: bad };
}
function readTips_() {
var out = [], bad = 0;
rows_('Tips').forEach(function (r) {
if (r[0] === '' && r[1] === '') return;
var date = Core.parseDate(r[0]), amount = Core.parseAmount(r[1], false), vat = r[3] === '' ? 0 : Core.parseAmount(r[3], false);
if (!date || amount == null || vat == null) { bad++; return; }
var type = str_(r[2]);
out.push({ date: date, amount: amount, type: Core.TYPES.indexOf(type) > -1 ? type : 'Card', vat: vat, source: str_(r[4]), ref: str_(r[5]) });
});
return { tips: out, bad: bad };
}
function readHours_() {
var out = [], bad = 0;
rows_('Hours').forEach(function (r) {
var name = str_(r[1]);
if (!name) return;
var h = Core.parseHours(r[2]), date = r[0] === '' ? null : Core.parseDate(r[0]);
if (h == null || (r[0] !== '' && !date)) { bad++; return; }
out.push({ date: date, name: name, hours: h });
});
return { hours: out, bad: bad };
}
/** 5.3: appends imported tips under the last row, skipping ones already there. */
function appendTips_(incoming) {
var have = readTips_().tips, d = Core.dedupe(have, incoming);
if (d.tips.length) {
var sh = ss_().getSheetByName('Tips');
var vals = d.tips.map(function (t) {
return [t.date, Core.plain(t.amount), t.type || 'Card', t.vat ? Core.plain(t.vat) : '', Core.safeText(t.source), Core.safeText(t.ref)];
});
var range = sh.getRange(sh.getLastRow() + 1, 1, vals.length, 6);
range.setValues(vals.map(function (r) { return [toDate_(r[0]), Number(r[1]), r[2], r[3] === '' ? '' : Number(r[3]), r[4], r[5]]; }));
sh.getRange(range.getRow(), 1, vals.length, 1).setNumberFormat('d mmm yyyy');
sh.getRange(range.getRow(), 2, vals.length, 1).setNumberFormat('0.00');
}
return { added: d.tips.length, skipped: d.skipped };
}
function toDate_(iso) { return new Date(+iso.slice(0, 4), +iso.slice(5, 7) - 1, +iso.slice(8, 10)); }
/** The Record sheet as text, from row 2. */
function recordValues_() {
var sh = ss_().getSheetByName('Record');
if (!sh) return [];
var n = sh.getLastRow() - 1;
return n > 0 ? sh.getRange(2, 1, n, HEADERS.Record.length).getDisplayValues() : [];
}
/** 6.8: adds a finalised block. An earlier block for the same period is marked Replaced, never deleted. */
function writeRecord_(rows, id, today) {
var sh = ss_().getSheetByName('Record'), old = recordValues_(), stamp = 'Replaced on ' + Core.d(today);
var all = old.map(function (r) {
var x = r.slice();
if (x[0] === id && !/^Replaced/.test(x[21])) x[21] = stamp;
return x;
}).concat(rows);
all = all.map(function (r) { return r.map(Core.safeText); });
sh.getRange(2, 1, all.length, HEADERS.Record.length).setNumberFormat('@').setValues(all);
}
/** "Write shares to sheet": a Shares sheet for payroll, replaced each time. */
function writeSharesSheet_(r, title) {
var ss = ss_(), sh = ss.getSheetByName('Shares') || ss.insertSheet('Shares');
sh.clearContents();
var vals = [[Core.safeText(title), '', '', '', ''], HEADERS.Shares];
r.people.forEach(function (p) { vals.push([Core.safeText(p.full), Core.safeText(p.group), Core.hundredths(p.h), Core.hundredths(p.p), p.share / 100]); });
sh.getRange(1, 1, vals.length, 5).setValues(vals);
sh.getRange(1, 1, 2, 5).setFontWeight('bold');
sh.getRange(3, 5, Math.max(r.people.length, 1), 1).setNumberFormat('0.00');
sh.setFrozenRows(2);
ss.setActiveSheet(sh);
}
/**
* Tip Fair licence (6.11). The sidebar talks to Freemius itself, so the add-on needs no
* external_request scope. This file keeps the result in Document Properties and decides Pro from it.
* Only the uid, the key and the title "Tip Fair" ever leave the sheet.
*/
/** Freemius product, made at launch in the Facilo store (21741). */
var LICENCE = { productId: '44992', apiBase: 'https://api.freemius.com/v1', title: 'Tip Fair' };
function lic_() {
var raw = PropertiesService.getDocumentProperties().getProperty('tfLicence');
return raw ? JSON.parse(raw) : {};
}
function saveLic_(l) { PropertiesService.getDocumentProperties().setProperty('tfLicence', JSON.stringify(l)); }
/** What the rest of the add-on asks: is Pro on today? */
function licenceState_(today) {
var l = lic_(), st;
if (!l.key) return { pro: false, status: 'none', hasKey: false, productId: LICENCE.productId };
if (l.status === 'ok') {
var expired = l.expires && l.expires < today, left = Core.GRACE_DAYS - Core.daysBetween(l.lastGood || today, today);
st = { pro: !expired && (l.lastFail ? left > 0 : true), status: expired ? 'expired' : 'ok', expires: l.expires || null, left: Math.max(0, left) };
} else st = { pro: false, status: l.status || 'wrong', expires: l.expires || null };
st.hasKey = true;
st.keyEnd = l.key.slice(-4);
st.needsCheck = l.status === 'ok' && (!l.lastCheck || l.lastCheck < today);
st.productId = LICENCE.productId;
return st;
}
/** What the sidebar sends to Freemius. */
function licenceRequest(key) {
var l = lic_();
return { ok: !!LICENCE.productId, uid: Core.uid(ss_().getId()), key: String(key || l.key || '').trim(), installId: l.installId || '',
productId: LICENCE.productId, apiBase: LICENCE.apiBase, title: LICENCE.title };
}
/**
* Stores what Freemius said. result.status: 'ok' | 'wrong' | 'used' | 'expired' | 'cancelled' | 'offline'.
* Offline keeps Pro for 14 days from the last good check (Core.GRACE_DAYS).
*/
function recordLicence(result) {
var l = lic_(), today = today_();
if (result.status === 'ok') {
l = { key: result.key || l.key, installId: String(result.installId || l.installId || ''), status: 'ok', expires: result.expires ? String(result.expires).slice(0, 10) : null, lastGood: today, lastCheck: today };
} else if (result.status === 'offline') {
if (l.status === 'ok') { l.lastFail = today; l.lastCheck = today; }
} else if (result.status === 'expired' || result.status === 'cancelled') {
l.status = result.status; l.lastCheck = today;
if (result.expires) l.expires = String(result.expires).slice(0, 10);
} else {
// A wrong key typed over a working one doesn't switch Pro off.
if (l.key && l.status === 'ok' && result.key && result.key !== l.key) return { pro: licenceState_(today).pro, status: result.status, hasKey: true };
l = { key: result.key || l.key, installId: l.installId || '', status: result.status || 'wrong', expires: l.expires || null, lastCheck: today };
}
saveLic_(l);
return licenceState_(today);
}
var HTML_FILES_ = {"Sidebar":"\n!= include('styles') ?>\n\n\n!= include('core') ?>\n\n\n","Print":"\n\n\n\n