https://script.google.com/a/macros/83d.in/s/AKfycbw6E_Abkiv30eDjINCLKizLKlcdXnqqY3B4372Eskh3g5CZJh3rsVDaS13pxAh1MrAY/exec

未關閉
#665 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

評估

難度
5/5
預估耗時
一週以上
新手友好度
1/100
Issue 類型
功能
描述清晰度
需要釐清
活躍度
活躍
技術堆疊
javascript
領域
api, backend

研究方向

The issue body contains a complete salary portal implementation and deployment instructions, but does not state what change is requested. Start by checking the issue title and repository context to identify the intended task; the payload names no tests or specific entry point to investigate. The work is ready to define only once the requested change and its completion criteria are clear.

由索引模型根據 Issue 內容生成。

描述

/* SALARY PORTAL - Milcom Defence Private Limited | Developed by Aaliyah Kama
FIRST RUN : select function "setup" > Run > authorize. (creates the data spreadsheet)
THEN : Deploy > New deployment > Web app > Execute as: Me, Access: Anyone.
AFTER ANY EDIT : Deploy > Manage deployments > pencil icon > Version: New version > Deploy.
First login : username admin password ADMIN123 (change it right away) */

const COLS = {
Users: ['username', 'hash', 'role', 'emp'],
Employees: ['name', 'designation', 'salary', 'active'],
Attendance: ['key', 'data'],
Travel: ['id', 'emp', 'from', 'to', 'days', 'co', 'note'],
Holidays: ['date', 'occasion']
};
let SS_ = null; // spreadsheet cached for the duration of one request (much faster)

function doGet() {
return HtmlService.createHtmlOutputFromFile('Index')
.setTitle('Salary Portal | Milcom Defence')
.addMetaTag('viewport', 'width=device-width,initial-scale=1');
}
function setup() { Logger.log('Data sheet: ' + ss_().getUrl()); }

function hash_(p) {
return Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, 'milcom|' + p)
.map(b => ('0' + (b & 255).toString(16)).slice(-2)).join('');
}
function ss_() {
if (SS_) return SS_;
const P = PropertiesService.getScriptProperties(), id = P.getProperty('SS');
if (id) return (SS_ = SpreadsheetApp.openById(id));
const s = SpreadsheetApp.create('Milcom Salary Portal Data');
Object.keys(COLS).forEach((n, i) => {
const sh = i ? s.insertSheet(n) : s.getSheets()[0].setName(n);
sh.getRange('A:Z').setNumberFormat('@'); // plain text: stops Sheets turning dates/numbers into other types
sh.appendRow(COLS[n]);
});
s.getSheetByName('Users').appendRow(['admin', hash_('ADMIN123'), 'admin', '']);
P.setProperty('SS', s.getId()); // saved only after everything was created
return (SS_ = s);
}
const tab_ = n => ss_().getSheetByName(n);
const str_ = v => v instanceof Date ? Utilities.formatDate(v, Session.getScriptTimeZone(), 'yyyy-MM-dd') : String(v);

function rows_(n) {
const v = tab_(n).getDataRange().getValues(), h = v.shift();
return v.filter(r => String(r[0]) !== '').map(r => { const o = {}; h.forEach((k, i) => o[k] = str_(r[i])); return o; });
}
function put_(n, list) {
const sh = tab_(n), c = COLS[n];
if (sh.getLastRow() > 1) sh.getRange(2, 1, sh.getLastRow() - 1, c.length).clearContent();
if (list.length) sh.getRange(2, 1, list.length, c.length).setValues(list.map(o => c.map(k => o[k] === undefined ? '' : o[k])));
}
// change ONE attendance record (fast: touches a single cell)
function attSet_(key, fn) {
const sh = tab_('Attendance'), v = sh.getDataRange().getValues();
const i = v.findIndex((r, j) => j && String(r[0]) === key);
const o = i > 0 ? JSON.parse(v[i][1]) : { c: {}, tds: 0, ot: 0 };
fn(o);
if (i > 0) sh.getRange(i + 1, 2).setValue(JSON.stringify(o)); else sh.appendRow([key, JSON.stringify(o)]);
}
// change MANY attendance records in one pass (used by travel add/remove)
function attMany_(keys, fn) {
const all = rows_('Attendance'), map = {};
all.forEach(r => map[r.key] = r);
keys.forEach(k => {
if (!map[k]) { map[k] = { key: k, data: JSON.stringify({ c: {}, tds: 0, ot: 0 }) }; all.push(map[k]); }
const o = JSON.parse(map[k].data); o.c = o.c || {};
fn(o, k);
map[k].data = JSON.stringify(o);
});
put_('Attendance', all);
}
function days_(a, b) {
const r = [];
for (let d = new Date(a + 'T00:00:00Z'), e = new Date(b + 'T00:00:00Z'); d <= e && r.length < 62; d.setUTCDate(d.getUTCDate() + 1))
r.push(d.toISOString().slice(0, 10));
return r;
}
function groupDays_(emp, D) {
const g = {};
D.forEach(d => (g[d.slice(0, 7) + '|' + emp] = g[d.slice(0, 7) + '|' + emp] || []).push(+d.slice(8)));
return g;
}

function login(u, p) {
const r = rows_('Users').find(x => x.username.toLowerCase() === String(u || '').trim().toLowerCase() && x.hash === hash_(String(p || '')));
if (!r) return { ok: false };
const t = Utilities.getUuid();
CacheService.getScriptCache().put(t, JSON.stringify({ u: r.username, role: r.role, emp: r.emp }), 21600);
return { ok: true, t: t };
}

const OPEN = ['load', 'changePass'];
function api(t, a, x) {
const raw = CacheService.getScriptCache().get(t);
if (!raw) throw new Error('Session expired - please log in again');
const s = JSON.parse(raw);
if (!Object.prototype.hasOwnProperty.call(ACT, a)) throw new Error('Unknown action');
if (OPEN.indexOf(a) < 0 && s.role !== 'admin') throw new Error('Admin only');
const L = LockService.getScriptLock();
L.waitLock(20000);
try { return ACT[a](s, x || {}); } finally { L.releaseLock(); }
}

const ACT = {
load(s, x) {
const adm = s.role === 'admin', ok = n => adm || n === s.emp;
const emps = rows_('Employees').filter(e => e.active !== 'no' && ok(e.name))
.map(e => ({ name: e.name, designation: e.designation, salary: +e.salary }));
const att = {}, comp = {};
rows_('Attendance').forEach(r => {
const i = r.key.indexOf('|'), ym = r.key.slice(0, i), n = r.key.slice(i + 1), o = JSON.parse(r.data);
if (!ok(n)) return;
for (const d in o.c) if (o.c[d] === 'CO') (comp[n] = comp[n] || { e: 0, u: 0 }).u++;
if (ym === x.ym) att[n] = o;
});
const trv = rows_('Travel').filter(t => ok(t.emp));
trv.forEach(t => (comp[t.emp] = comp[t.emp] || { e: 0, u: 0 }).e += +t.co || 0);
const hol = rows_('Holidays').sort((a, b) => a.date < b.date ? -1 : 1);
return { me: s, emps, att, trv, comp, hol, users: adm ? rows_('Users').map(u => u.username) : [] };
},
setCode(s, x) {
attSet_(x.ym + '|' + x.emp, o => {
if (o.c[x.day] === 'T') return;
if (x.code) o.c[x.day] = x.code; else delete o.c[x.day];
});
},
setExtra(s, x) {
if (['tds', 'ot'].indexOf(x.f) < 0) throw new Error('Bad field');
attSet_(x.ym + '|' + x.emp, o => { o[x.f] = Math.max(0, +x.v || 0); });
},
addEmp(s, x) {
const name = String(x.name || '').trim().toUpperCase(), sal = +x.salary;
if (!name || !(sal > 0)) throw new Error('Enter a name and a monthly salary');
const E = rows_('Employees'), U = rows_('Users'), un = name.toLowerCase().replace(/\s+/g, '');
if (E.some(e => e.name === name && e.active !== 'no') || U.some(u => u.username.toLowerCase() === un))
throw new Error('This employee already exists');
const E2 = E.filter(e => e.name !== name); // drop an old removed record of the same name
E2.push({ name, designation: x.desig || '', salary: sal, active: 'yes' });
U.push({ username: un, hash: hash_('milcom123'), role: 'emp', emp: name });
put_('Employees', E2); put_('Users', U);
},
editEmp(s, x) {
const sal = +x.salary;
if (!(sal > 0)) throw new Error('Enter a valid salary');
put_('Employees', rows_('Employees').map(e => e.name === x.name ? Object.assign(e, { designation: x.desig, salary: sal }) : e));
},
removeEmp(s, x) {
put_('Employees', rows_('Employees').map(e => e.name === x.name ? Object.assign(e, { active: 'no' }) : e));
put_('Users', rows_('Users').filter(u => u.emp !== x.name));
},
setPass(s, x) {
if (String(x.pw || '').length < 4) throw new Error('Password needs at least 4 characters');
const U = rows_('Users'), u = U.find(r => r.username === x.user);
if (!u) throw new Error('User not found');
u.hash = hash_(x.pw); put_('Users', U);
},
changePass(s, x) {
if (String(x.pw || '').length < 4) throw new Error('Password needs at least 4 characters');
const U = rows_('Users'), u = U.find(r => r.username === s.u);
if (!u || u.hash !== hash_(String(x.old || ''))) throw new Error('Current password is wrong');
u.hash = hash_(x.pw); put_('Users', U);
},
addHoliday(s, x) {
if (!x.date || !x.occ) throw new Error('Enter a date and an occasion');
const H = rows_('Holidays').filter(h => h.date !== x.date);
H.push({ date: x.date, occasion: x.occ }); put_('Holidays', H);
},
removeHoliday(s, x) { put_('Holidays', rows_('Holidays').filter(h => h.date !== x.date)); },
addTravel(s, x) {
if (!x.emp || !x.from || !x.to || x.to < x.from) throw new Error('Choose an employee and a valid date range');
const D = days_(x.from, x.to), g = groupDays_(x.emp, D);
attMany_(Object.keys(g), (o, k) => g[k].forEach(n => o.c[n] = 'T'));
const T = rows_('Travel');
T.push({ id: Utilities.getUuid().slice(0, 8), emp: x.emp, from: x.from, to: x.to, days: D.length, co: +x.co || 0, note: x.note || '' });
put_('Travel', T);
},
removeTravel(s, x) {
const T = rows_('Travel'), t = T.find(r => r.id === x.id);
if (!t) return;
const g = groupDays_(t.emp, days_(t.from, t.to));
attMany_(Object.keys(g), (o, k) => g[k].forEach(n => { if (o.c[n] === 'T') delete o.c[n]; }));
put_('Travel', T.filter(r => r.id !== x.id));
}
};

主要語言
JavaScript
星號
5.3k
分支
2k
PR 合併指標
30 天內沒有已合併 PR

環境準備

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

googleworkspace/apps-script-samples 的其他 Issue

查看 googleworkspace/apps-script-samples 的全部 Issue

相似的 Issue

更多 JavaScript Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。