@mytools-all/mytools-clock 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MyTools Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # 打卡
2
+
3
+ MyTools 独立静态插件,当前版本 0.1.0,源码仓库为 [mytools-all/mytools-clock](https://github.com/mytools-all/mytools-clock),npm 包为 `@mytools-all/mytools-clock`。依据宿主公开插件开发文档和 Demo 开发,不依赖宿主源码。
4
+
5
+ ## 使用
6
+
7
+ - 上班、下班成对记录,支持一天多段、跨天、补录、修改、确认删除。午休等多段工时可通过复杂页面的补录和修改维护,间隔不计工时。
8
+ - 保存每日目标工时;当前未结束记录显示最早下班时间,减去其上班日期已经完成的工时。独立计算器可额外输入已完成分钟和休息分钟,不创建打卡记录。
9
+ - 日、周(月曜日起)、月、季度、年、指定起止日期统计,日期包含首尾。跨天记录按自然日边界拆分;未结束记录单独提示,不计入工时。明细显示整对时长,统计卡显示范围内时长。
10
+ - Markdown 与 Excel XML(.xml,Excel 可直接打开)导出当前范围统计和相交记录;JSON 导出完整记录和每日目标,用于备份,不受统计范围限制。目前没有二进制 .xlsx 或 Markdown 导入。
11
+ - JSON 导入先校验并预览,确认后合并;同 ID 记录采用导入内容,其他记录保留,现有目标工时保留。时间冲突、重复 ID、多个未完成记录、无效日期、未知版本均拒绝整批导入。重复导入不会重复创建记录。
12
+
13
+ ## 安装和数据
14
+
15
+ 执行 `npm ci`、`npm test`、`npm pack`,在 MyTools → 插件中心 → 开发者安装生成的 tgz,重新扫描并搜索“打卡”。也可复制完整包目录至宿主插件目录,再扫描。无需 npm 发布。
16
+
17
+ 仅声明 storage.get、storage.set、fs.exporttext。数据保存在宿主按插件隔离的 clock.state.v1;JSON 文件通过浏览器原生文件选择控件读取,不自行访问任意路径。导出使用宿主系统保存对话框,支持取消。加载前禁写,校验失败不覆盖,保存成功后才更新内存;不依赖退出保存。
18
+
19
+ 时间采用本机民用日期和时分,精确到分钟;统计按相同民用时间解释,不处理跨时区旅行及夏令时的真实经过时长。不自动扣除午休,不连接公司考勤系统。即时上、下班至少相隔一分钟。多窗口不具备并发合并保证,请顺序编辑并重新载入。最多 10000 条记录,导入最多 4 MB,导出受宿主 8 MB 限制。
20
+
21
+ ## 验证
22
+
23
+ Node 纯逻辑与 happy-dom 模拟桥接覆盖跨天跨月、闰年、周期边界、工时计算、记录冲突、备份往返、导入确认、保存失败及文本转义。模拟测试不等于 Windows 原生验收;系统保存对话框、真实 Excel 打开、原生文件选择、嵌入/分离和重新启动仍需实际验证。
24
+
25
+ 代码 MIT,happy-dom 仅为开发依赖,不随插件包交付。
26
+
27
+ ## 页面与下班规则(0.1.0)
28
+
29
+ 右上角“设置”打开侧边栏,可保存简洁 / 复杂页面。新数据默认简洁页面,只显示即时上下班、当天工作时长和下班条件;已有 v1 数据迁移时保留复杂页面。复杂页面提供补录、修改、计算器、统计和导入导出。
30
+
31
+ 下班条件二选一:每日工时(默认 8 小时),或固定下班时间(默认 18:00)。即时下班操作在按钮和实际处理逻辑中均校验条件,未满足时禁止;界面每分钟随时间更新可用状态。工时模式按当前记录上班日期的已完成工时抵扣;跨夜连续记录仍属于原上班日期的目标。固定模式按上班日期的指定时刻判断,例如 18:00 前禁止、18:00 起允许;18:00 后才上班则至少一分钟后可下班,不自动推迟到翌日。夜班可使用工时模式。
32
+
33
+ 当天工时为本日已完成工时加当前未完成记录在本日的经过时长,统计导出仍只计算完成记录。补录、修改和导入用于整理历史数据,不受即时下班门槛限制。新配置字段与记录一并备份,导入合并仍保留当前页面和下班规则;保存失败不更新设置。重新载入或重新打开后设置保留。插件离开时停止计时,重新进入时恢复,不写计时中间值。
package/app.mjs ADDED
@@ -0,0 +1,81 @@
1
+ import {dayKey,localStamp,minute,stamp,parseState,saveRecord,period,statistics,earliest,duration,checkoutStatus,checkoutRecord} from './model.mjs';
2
+ import {createStore} from './storage.mjs';
3
+ import {exportRecords,readImport,mergeRecords} from './transfer.mjs';
4
+
5
+ export function createClock(doc,api,now=()=>new Date()) {
6
+ const $=s=>doc.querySelector(s);
7
+ const call=async(id,args)=>{if(!api) throw Error('请从 MyTools 打开此插件');return api.call(id,args);};
8
+ const store=createStore(call);let editId;let confirmAction;let initialized=false;
9
+ const status=(text,error=false)=>{$('#status').textContent=text;$('#status').dataset.error=String(error);};
10
+ const report=e=>status(e?.message||String(e),true);
11
+ const action=fn=>async event=>{try{await fn(event);}catch(e){report(e);}};
12
+ const node=(tag,text)=>{const el=doc.createElement(tag);if(text!==undefined)el.textContent=text;return el;};
13
+ const range=()=>period($('#period').value,$('#anchor').value,$('#from').value,$('#to').value);
14
+ function writable(){doc.querySelectorAll('[data-write]').forEach(el=>{el.disabled=!store.state||store.busy;});if(store.state){const open=store.state.records.some(r=>!r.end);$('#punch-in').disabled=store.busy||open;$('#punch-out').disabled=store.busy||!open||!checkoutStatus(store.state,localStamp(now())).allowed;}}
15
+ function clearEdit(){editId=undefined;$('#form-title').textContent='补录打卡';$('#record-start').value=localStamp(now());$('#record-end').value='';$('#record-note').value='';}
16
+ async function save(next){const pending=store.save(next);writable();try{await pending;render();status('已保存到本机');}finally{writable();}}
17
+ function showConfirmation(title,text,fn){$('#confirm-title').textContent=title;$('#confirm-text').textContent=text;confirmAction=fn;$('#confirm-dialog').showModal();}
18
+ function calculate(){$('#calc-result').textContent='—';const value=earliest($('#calc-start').value,Math.round(Number($('#target').value)*60),Number($('#completed').value),Number($('#break').value));$('#calc-result').textContent=value.replace('T',' ');}
19
+ function render(){
20
+ writable();if(!store.state)return;
21
+ const state=store.state,open=state.records.find(r=>!r.end);
22
+ doc.body.dataset.view=state.viewMode;
23
+ renderLive(true);
24
+ $('#current').textContent=open?'工作进行中':'尚未上班';
25
+ const custom=$('#period').value==='custom';$('#anchor').disabled=custom;$('#from').disabled=$('#to').disabled=!custom;
26
+ const r=range(),stats=statistics(state,r);
27
+ $('#range-caption').textContent=`${stamp(r.start).slice(0,10)} 至 ${stamp(r.end-1).slice(0,10)}(含首尾日期,周一为每周起点)`;
28
+ $('#total').textContent=duration(stats.totalMinutes);$('#days').textContent=String(stats.days.length);$('#pairs').textContent=String(stats.pairs);
29
+ $('#pending').textContent=stats.pending?`${stats.pending} 条未下班记录,未计入已完成工时。`: '所有范围内记录均已成对。';
30
+ $('#daily').replaceChildren(...stats.days.map(d=>node('span',`${d.date} · ${duration(d.minutes)}`)));
31
+ const records=state.records.filter(record=>minute(record.start)<r.end&&(!record.end||minute(record.end)>r.start)).sort((a,b)=>b.start.localeCompare(a.start));
32
+ $('#records').replaceChildren(...records.map(record=>{
33
+ const row=node('div');row.className='record';const content=node('div');content.className='record-content';content.append(node('strong',record.start.replace('T',' ')+' → '+(record.end?.replace('T',' ')||'未下班')),node('p',(record.end?duration(minute(record.end)-minute(record.start)):'进行中')+(record.note?' · '+record.note:'')));
34
+ const edit=node('button','修改');edit.dataset.write='';edit.onclick=()=>{editId=record.id;$('#form-title').textContent='修改打卡';$('#record-start').value=record.start;$('#record-end').value=record.end||'';$('#record-note').value=record.note;$('#record-start').focus();};
35
+ const remove=node('button','删除');remove.className='danger';remove.dataset.write='';remove.onclick=()=>showConfirmation('删除打卡记录','将删除这一对打卡记录,工时统计会同步更新。',async()=>{const next=structuredClone(store.state);next.records=next.records.filter(r=>r.id!==record.id);await save(next);if(editId===record.id)clearEdit();});row.append(content,edit,remove);return row;
36
+ }));
37
+ if(!records.length)$('#records').append(node('p','这个范围还没有打卡记录。'));
38
+ writable();
39
+ }
40
+ async function load(){if(store.busy)return;const pending=store.load();writable();try{await pending;initialized=true;$('#target').value=String(store.state.targetMinutes/60);render();status('已载入 · 修改后自动保存');}finally{writable();}}
41
+ let lastLiveState,lastLiveMinute;
42
+ function renderLive(force=false){
43
+ if(!store.state)return;
44
+ const currentMinute=localStamp(now());
45
+ if(!force && lastLiveState===store.state && lastLiveMinute===currentMinute)return;
46
+ lastLiveState=store.state;lastLiveMinute=currentMinute;
47
+ const state=store.state,value=checkoutStatus(state,localStamp(now()));
48
+ $('#today-work').textContent=duration(value.todayMinutes);
49
+ $('#prediction').textContent=value.open?`上班 ${value.open.start.replace('T',' ')} · 最早下班 ${value.threshold.replace('T',' ')}`:(state.ruleMode==='fixed'?`固定下班时间 ${state.fixedTime}`:`每日目标 ${duration(state.targetMinutes)}`);
50
+ $('#checkout-hint').textContent=value.open?(value.allowed?'已满足下班条件,可以下班打卡。':`还需等待 ${duration(value.remaining)},到点后可下班打卡。`):'点击上班打卡开始记录。';
51
+ writable();
52
+ }
53
+ function renderRule(){const fixed=$('#setting-rule').value==='fixed';$('#setting-hours-label').hidden=fixed;$('#setting-time-label').hidden=!fixed;$('#setting-rule-hint').textContent=fixed?'例如设置 18:00:当天 18:00 前禁止下班,到点后允许。':'累计当天已完成工时与当前这段工时,达到目标后允许下班。';}
54
+ $('#open-settings').onclick=()=>{if(!store.state){report(Error('请先载入数据'));return;}const state=store.state;$('#setting-view').value=state.viewMode;$('#setting-rule').value=state.ruleMode;$('#setting-hours').value=String(state.targetMinutes/60);$('#setting-time').value=state.fixedTime;$('#settings-error').textContent='';renderRule();$('#settings-drawer').showModal();};
55
+ $('#close-settings').onclick=()=>$('#settings-drawer').close();
56
+ $('#setting-rule').onchange=renderRule;
57
+ $('#settings-form').onsubmit=async event=>{event.preventDefault();try{const next={...store.state,viewMode:$('#setting-view').value,ruleMode:$('#setting-rule').value,targetMinutes:Math.round(Number($('#setting-hours').value)*60),fixedTime:$('#setting-time').value};await save(parseState(next));$('#target').value=String(store.state.targetMinutes/60);$('#settings-drawer').close();}catch(e){$('#settings-error').textContent=e.message;report(e);}};
58
+ let timer;
59
+ function startTimer(){if(timer===undefined)timer=doc.defaultView?.setInterval(()=>{try{renderLive();}catch(e){report(e);}},1000);}
60
+ function dispose(){if(timer!==undefined)doc.defaultView?.clearInterval(timer);timer=undefined;}
61
+ startTimer();api?.onPluginOut?.(dispose);api?.onPluginEnter?.(startTimer);
62
+ $('#punch-in').onclick=action(async()=>{await save(saveRecord(store.state,{start:localStamp(now()),end:null,note:''}));});
63
+ $('#punch-out').onclick=action(async()=>{await save(checkoutRecord(store.state,localStamp(now())));});
64
+ $('#record-form').onsubmit=action(async event=>{event.preventDefault();await save(saveRecord(store.state,{id:editId,start:$('#record-start').value,end:$('#record-end').value,note:$('#record-note').value}));clearEdit();});
65
+ $('#cancel-edit').onclick=clearEdit;
66
+ $('#calculator').onsubmit=action(event=>{event.preventDefault();calculate();});
67
+ $('#save-target').onclick=action(async()=>{const next=structuredClone(store.state);next.targetMinutes=Math.round(Number($('#target').value)*60);await save(parseState(next));calculate();});
68
+ for(const id of ['period','anchor','from','to'])$('#'+id).onchange=action(()=>render());
69
+ $('#reload').onclick=action(load);
70
+ $('#export').onclick=action(async()=>{if(!store.state||store.busy)throw Error('请先载入数据并等待保存完成');const result=await call('fs.exporttext',exportRecords(store.state,$('#export-format').value,range()));status(result?.cancelled?'已取消导出':'打卡数据已导出');});
71
+ $('#import-file').onchange=action(async()=>{const input=$('#import-file');const file=input.files?.[0];input.value='';if(!file)return;if(!store.state||store.busy)throw Error('请先载入数据');if(file.size>4*1024*1024)throw Error('导入文件不能超过 4 MB');const imported=readImport(await file.text());mergeRecords(store.state,imported);showConfirmation('导入打卡备份',`将合并 ${imported.records.length} 条记录。同 ID 以导入内容为准,保留现有每日目标。若时间重叠则不导入。`,async()=>{await save(mergeRecords(store.state,imported));});});
72
+ $('#confirm-action').onclick=action(async()=>{if(!confirmAction)return;await confirmAction();confirmAction=undefined;$('#confirm-dialog').close();});
73
+ $('#confirm-cancel').onclick=()=>{$('#confirm-dialog').close();confirmAction=undefined;};
74
+ $('#calc-start').value=localStamp(now());$('#anchor').value=$('#from').value=$('#to').value=dayKey(now());clearEdit();writable();
75
+ try{calculate();}catch(e){report(e);}
76
+ if(api)api.onPluginReady(()=>{if(!initialized)void load().catch(report);});else status('网页预览 · 请从 MyTools 打开以保存记录');
77
+ return {store,load,render,tick:renderLive,dispose};
78
+ }
79
+ if(typeof window!=='undefined'&&typeof document!=='undefined'){
80
+ try{createClock(document,window.mytools);}catch(e){document.querySelector('#status').textContent='打卡初始化失败:'+e.message;}
81
+ }
package/icon.svg ADDED
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96"><rect width="96" height="96" rx="24" fill="#4f46e5"/><circle cx="48" cy="46" r="28" fill="none" stroke="#fff" stroke-width="5"/><path d="M48 28v19l13 8" fill="none" stroke="#fff" stroke-width="5" stroke-linecap="round"/><path d="m59 72 8 8 16-20" fill="none" stroke="#34d399" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/></svg>
package/index.html ADDED
@@ -0,0 +1,12 @@
1
+ <!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>打卡</title><link rel="stylesheet" href="./style.css"><script type="module" src="./app.mjs"></script></head><body>
2
+ <header><div class="brand"><img src="./icon.svg" alt=""><div><h1>打卡</h1><p>记录每一次投入,也准时结束工作</p></div></div><div class="actions"><button id="reload">重新载入</button><button id="open-settings" aria-label="打开打卡设置">⚙ 设置</button></div></header>
3
+ <main>
4
+ <section class="card punch"><div><span class="eyebrow">当前状态</span><h2 id="current">正在读取…</h2><p id="prediction">先设置目标工时,再记录上下班</p></div><div class="actions"><button id="punch-in" data-write class="primary">上班打卡</button><button id="punch-out" data-write>下班打卡</button></div><div class="today-work"><span>当天工作时长</span><strong id="today-work">—</strong><p id="checkout-hint"></p></div><p class="hint complex-only">午休请通过补录维护多段工时。即时下班必须达到设置条件;所有记录使用本机民用时间,精确到分钟。</p></section>
5
+ <div class="columns complex-only"><section class="card"><h2>最早下班时间</h2><form id="calculator"><label>上班时间<input id="calc-start" type="datetime-local" required></label><div class="fields"><label>每日目标(小时)<input id="target" type="number" min="0.0167" max="24" step="any" value="8" required></label><label>另加休息(分钟)<input id="break" type="number" min="0" max="1440" step="1" value="0" required></label></div><label>已完成工时(分钟)<input id="completed" type="number" min="0" step="1" value="0" required></label><div class="actions"><button type="submit">计算</button><button id="save-target" data-write type="button">保存每日目标</button></div><output id="calc-result">—</output></form><p class="hint">最早下班 = 上班时间 + 尚需工时 + 另加休息。计算器不自动创建记录。</p></section>
6
+ <section class="card"><h2 id="form-title">补录打卡</h2><form id="record-form"><label>上班时间<input id="record-start" type="datetime-local" required data-write></label><label>下班时间(可留空,表示尚未下班)<input id="record-end" type="datetime-local" data-write></label><label>备注<input id="record-note" maxlength="300" data-write placeholder="项目、加班说明…"></label><div class="actions"><button type="submit" class="primary" data-write>保存记录</button><button type="button" id="cancel-edit">取消编辑</button></div></form><p class="hint">时间段不可重叠;最多保留一条未完成记录,可修改或删除错误记录。</p></section></div>
7
+ <section class="card complex-only"><div class="section-title"><h2>工时统计</h2><select id="period" aria-label="统计周期"><option value="day">日</option><option value="week">周</option><option value="month" selected>月</option><option value="quarter">季度</option><option value="year">年</option><option value="custom">指定时间段</option></select></div><div class="fields"><label id="anchor-label">参考日期<input id="anchor" type="date"></label><label>开始日期<input id="from" type="date"></label><label>结束日期<input id="to" type="date"></label></div><p id="range-caption" class="hint"></p><div class="metrics"><div><span>已完成工时</span><strong id="total">—</strong></div><div><span>有记录天数</span><strong id="days">0</strong></div><div><span>完成打卡对数</span><strong id="pairs">0</strong></div></div><p id="pending" class="hint"></p><div id="daily" class="daily"></div><div class="actions transfer"><select id="export-format" aria-label="导出格式"><option value="md">Markdown</option><option value="excel">Excel(XML)</option><option value="json">JSON 完整备份</option></select><button id="export" data-write>导出</button><label class="file-label">导入 JSON<input id="import-file" type="file" accept=".json,application/json" data-write></label></div><p class="hint">MD / Excel 导出当前统计范围及相交记录;JSON 备份全部记录和目标工时。跨天工时按自然日拆分,未下班记录不计入工时。</p></section>
8
+ <section class="card complex-only"><h2>范围内打卡记录</h2><div id="records" class="records"></div></section>
9
+ </main><footer><p id="status" role="status"></p><span>本机保存 · 多窗口请顺序编辑,重新载入获取最新数据</span></footer>
10
+ <dialog id="settings-drawer" class="settings-drawer" aria-label="打卡设置"><div class="section-title"><h2>打卡设置</h2><button id="close-settings" aria-label="关闭打卡设置">×</button></div><form id="settings-form"><label>页面模式<select id="setting-view" data-write><option value="simple">简洁页面</option><option value="complex">复杂页面</option></select></label><p class="hint">简洁页面只展示上下班打卡和当天工时,复杂页面包含计算器、补录、统计及导入导出。</p><label>下班条件<select id="setting-rule" data-write><option value="duration">每日必须完成的工时</option><option value="fixed">固定下班时间</option></select></label><label id="setting-hours-label">每日工时(小时)<input id="setting-hours" type="number" min="0.0167" max="24" step="any" value="8" data-write></label><label id="setting-time-label">固定下班时间<input id="setting-time" type="time" value="18:00" data-write></label><p id="setting-rule-hint" class="hint"></p><p class="hint">条件未满足时禁止即时下班。补录和修改用于纠正记录,不受即时打卡限制。规则按当前未完成记录的上班日期计算。</p><p id="settings-error" role="alert"></p><button class="primary" type="submit" data-write>保存设置</button></form></dialog>
11
+ <dialog id="confirm-dialog"><h2 id="confirm-title"></h2><p id="confirm-text"></p><div class="actions"><button id="confirm-action" class="primary" data-write>确认</button><button id="confirm-cancel">取消</button></div></dialog>
12
+ </body></html>
package/model.mjs ADDED
@@ -0,0 +1,85 @@
1
+ export const pad = n => String(n).padStart(2,'0');
2
+ export const dayKey = d => `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`;
3
+ export const localStamp = d => `${dayKey(d)}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
4
+ export function minute(value) {
5
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) throw Error('请输入有效日期和时间');
6
+ const date = new Date(value+'Z');
7
+ if (!Number.isFinite(+date) || date.toISOString().slice(0,16)!==value || value<'1901' || value>'2099-12-31T23:59') throw Error('日期和时间无效(1901—2099 年)');
8
+ return +date/60000;
9
+ }
10
+ export const stamp = n => new Date(n*60000).toISOString().slice(0,16);
11
+ export function initialState() { return {version:1,targetMinutes:480,viewMode:'simple',ruleMode:'duration',fixedTime:'18:00',records:[]}; }
12
+ export function parseState(value) {
13
+ if (value===null) return initialState();
14
+ if (!value || value.version!==1 || !Number.isInteger(value.targetMinutes) || value.targetMinutes<1 || value.targetMinutes>1440 || !Array.isArray(value.records) || value.records.length>10000) throw Error('打卡数据无效或版本不支持,已停止写入');
15
+ const viewMode=value.viewMode ?? 'complex',ruleMode=value.ruleMode ?? 'duration',fixedTime=value.fixedTime ?? '18:00';
16
+ if (!['simple','complex'].includes(viewMode) || !['duration','fixed'].includes(ruleMode) || typeof fixedTime!=='string' || !/^([01]\d|2[0-3]):[0-5]\d$/.test(fixedTime)) throw Error('打卡设置无效');
17
+ const result = structuredClone(value); const ids = new Set(); let end = -Infinity;
18
+ const sorted = [...result.records].sort((a,b)=>String(a?.start).localeCompare(String(b?.start)));
19
+ for (const record of sorted) {
20
+ if (!record || typeof record.id!=='string' || !record.id || record.id.length>128 || ids.has(record.id) || typeof record.note!=='string' || record.note.length>300) throw Error('打卡记录无效');
21
+ const start = minute(record.start), finish = record.end===null ? Infinity : minute(record.end);
22
+ if (finish<=start || start<end) throw Error('打卡时间重叠、顺序错误或存在多条未完成记录');
23
+ ids.add(record.id); end=finish;
24
+ }
25
+ return {version:1,targetMinutes:result.targetMinutes,viewMode,ruleMode,fixedTime,records:result.records.map(({id,start,end,note})=>({id,start,end,note}))};
26
+ }
27
+ export function saveRecord(state, record) {
28
+ const next = structuredClone(state);
29
+ const item = {id:record.id || crypto.randomUUID(),start:record.start,end:record.end || null,note:record.note.trim()};
30
+ const index=next.records.findIndex(r=>r.id===item.id);
31
+ if (index<0) next.records.push(item); else next.records[index]=item;
32
+ return parseState(next);
33
+ }
34
+ export function period(kind, anchor, from, to) {
35
+ const base = minute(anchor+'T00:00'); const d=new Date(base*60000); let start=base,end=base+1440;
36
+ if (kind==='week') { start-=((d.getUTCDay()+6)%7)*1440; end=start+7*1440; }
37
+ else if (['month','quarter','year'].includes(kind)) {
38
+ const y=d.getUTCFullYear(), m=kind==='year'?0:kind==='quarter'?Math.floor(d.getUTCMonth()/3)*3:d.getUTCMonth();
39
+ start=Date.UTC(y,m,1)/60000;end=Date.UTC(y,m+(kind==='year'?12:kind==='quarter'?3:1),1)/60000;
40
+ } else if (kind==='custom') { start=minute(from+'T00:00');end=minute(to+'T00:00')+1440; if(end<=start) throw Error('结束日期不能早于开始日期'); }
41
+ else if (kind!=='day') throw Error('统计范围无效');
42
+ return {start,end};
43
+ }
44
+ export function statistics(value, range) {
45
+ const state=parseState(value);const days=new Map();let count=0;
46
+ for (const record of state.records) {
47
+ if (!record.end) continue;
48
+ let start=Math.max(minute(record.start),range.start); const end=Math.min(minute(record.end),range.end);
49
+ if(start>=end) continue;
50
+ count++;
51
+ while(start<end) { const boundary=Math.min((Math.floor(start/1440)+1)*1440,end);const key=stamp(start).slice(0,10);days.set(key,(days.get(key)||0)+boundary-start);start=boundary; }
52
+ }
53
+ const rows=[...days].sort(([a],[b])=>a.localeCompare(b)).map(([date,minutes])=>({date,minutes}));
54
+ return {days:rows,totalMinutes:rows.reduce((n,r)=>n+r.minutes,0),pairs:count,pending:state.records.filter(r=>!r.end && minute(r.start)<range.end).length};
55
+ }
56
+ export function earliest(start,targetMinutes,completed=0,breakMinutes=0) {
57
+ if (![targetMinutes,completed,breakMinutes].every(Number.isFinite) || targetMinutes<=0 || targetMinutes>1440 || completed<0 || breakMinutes<0 || breakMinutes>1440) throw Error('工时或休息时长无效');
58
+ const result=stamp(minute(start)+Math.max(0,Math.round(targetMinutes-completed))+Math.round(breakMinutes));
59
+ minute(result); return result;
60
+ }
61
+ export const duration = minutes => `${Math.floor(minutes/60)} 小时 ${minutes%60} 分钟`;
62
+
63
+ export function checkoutStatus(value, nowValue) {
64
+ const state=parseState(value),now=minute(nowValue),open=state.records.find(r=>r.end===null);
65
+ const day=period('day',nowValue.slice(0,10));
66
+ const completedToday=statistics(state,day).totalMinutes;
67
+ const currentToday=open?Math.max(0,now-Math.max(minute(open.start),day.start)):0;
68
+ if (!open) return {open:null,todayMinutes:completedToday,allowed:false,remaining:0,threshold:null};
69
+ const start=minute(open.start);
70
+ let threshold;
71
+ if(state.ruleMode==='fixed') {
72
+ threshold=minute(open.start.slice(0,10)+'T'+state.fixedTime);
73
+ } else {
74
+ const completed=statistics(state,period('day',open.start.slice(0,10))).totalMinutes;
75
+ threshold=start+Math.max(0,state.targetMinutes-completed);
76
+ }
77
+ threshold=Math.max(start+1,threshold);
78
+ return {open,todayMinutes:completedToday+currentToday,allowed:now>=threshold,remaining:Math.max(0,threshold-now),threshold:stamp(threshold)};
79
+ }
80
+ export function checkoutRecord(state, nowValue) {
81
+ const status=checkoutStatus(state,nowValue);
82
+ if(!status.open) throw Error('请先上班打卡');
83
+ if(!status.allowed) throw Error(`尚未达到下班条件,最早 ${status.threshold.replace('T',' ')} 可打卡`);
84
+ return saveRecord(state,{...status.open,end:nowValue});
85
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
- {
2
- "name": "@mytools-all/mytools-clock",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@mytools-all/mytools-clock",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "index.html",
6
+ "license": "MIT",
7
+ "description": "成对记录上下班,计算最早下班时间与多周期工时统计",
8
+ "files": [
9
+ "plugin.json",
10
+ "index.html",
11
+ "*.mjs",
12
+ "style.css",
13
+ "icon.svg",
14
+ "LICENSE",
15
+ "README.md"
16
+ ],
17
+ "scripts": {
18
+ "test": "node --test tests/*.test.mjs"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "devDependencies": {
24
+ "happy-dom": "21.0.4"
25
+ },
26
+ "author": "MyTools",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/mytools-all/mytools-clock.git"
30
+ },
31
+ "homepage": "https://github.com/mytools-all/mytools-clock#readme",
32
+ "bugs": {
33
+ "url": "https://github.com/mytools-all/mytools-clock/issues"
34
+ }
35
+ }
package/plugin.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "mytools-clock",
3
+ "pluginName": "打卡",
4
+ "description": "成对记录上下班,计算最早下班时间与多周期工时统计",
5
+ "version": "0.1.0",
6
+ "author": "MyTools",
7
+ "main": "index.html",
8
+ "icon": "icon.svg",
9
+ "apiVersion": 1,
10
+ "capabilities": [
11
+ "storage.get",
12
+ "storage.set",
13
+ "fs.exporttext"
14
+ ],
15
+ "features": [
16
+ {
17
+ "code": "clock",
18
+ "explain": "上下班打卡与工时统计",
19
+ "cmds": [
20
+ "打卡",
21
+ "上班打卡",
22
+ "工时",
23
+ "clock"
24
+ ]
25
+ }
26
+ ]
27
+ }
package/storage.mjs ADDED
@@ -0,0 +1,8 @@
1
+ import {parseState} from './model.mjs';
2
+ export function createStore(call) {
3
+ let state, busy=false;
4
+ return {get state(){return state;},get busy(){return busy;},
5
+ async load(){if(busy) throw Error('正在读写');busy=true;state=undefined;try{state=parseState(await call('storage.get',{key:'clock.state.v1'}));return state;}finally{busy=false;}},
6
+ async save(next){if(!state || busy) throw Error('请先载入数据并等待保存完成');const checked=parseState(next);busy=true;try{await call('storage.set',{key:'clock.state.v1',value:checked});state=checked;}finally{busy=false;}}
7
+ };
8
+ }
package/style.css ADDED
@@ -0,0 +1,3 @@
1
+ :root{font-family:Inter,"Microsoft YaHei",sans-serif;color-scheme:light dark;--bg:#f4f5fa;--card:#fff;--fg:#252b3d;--muted:#72788a;--border:#e4e7ef;--accent:#5852df;--soft:#eeedff;color:var(--fg);background:var(--bg)}*{box-sizing:border-box}body{margin:0}header,main,footer{max-width:1080px;margin:auto;padding:20px 24px}header,.brand,.section-title,.actions{display:flex;align-items:center;gap:10px}header{justify-content:space-between}.brand img{width:44px;height:44px}.brand h1{font-size:21px;margin:0}.brand p{margin:5px 0 0;color:var(--muted);font-size:12px}main{display:grid;gap:16px;padding-top:0}.card{background:var(--card);border:1px solid var(--border);border-radius:13px;padding:20px;min-width:0}.card h2{font-size:15px;margin:0 0 16px}.punch{background:linear-gradient(120deg,var(--soft),var(--card));display:grid;grid-template-columns:1fr auto;align-items:center;gap:12px}.punch h2{font-size:23px;margin:8px 0}.punch p{margin:0;color:var(--muted);font-size:13px}.punch .hint{grid-column:1/-1}.eyebrow{font-size:12px;color:var(--accent)}.columns{display:grid;grid-template-columns:1fr 1fr;gap:16px}.fields{display:flex;gap:12px;flex-wrap:wrap}.fields label{flex:1;min-width:130px}label{display:block;font-size:12px;color:var(--muted);margin-bottom:12px}input,select,button{font:inherit;font-size:13px;border:1px solid var(--border);border-radius:7px;color:var(--fg);background:var(--card);min-width:0}input,select{height:36px;padding:6px 9px}label input{display:block;width:100%;margin-top:7px}button{padding:8px 13px;cursor:pointer;white-space:nowrap}button:hover{border-color:var(--accent);color:var(--accent)}button.primary{background:var(--accent);color:white;border-color:var(--accent)}button:disabled,input:disabled{opacity:.5;cursor:default}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.actions{flex-wrap:wrap}.hint{color:var(--muted);font-size:12px;line-height:1.8;margin:12px 0 0}output{display:block;margin-top:16px;color:var(--accent);font-size:20px;font-weight:600}.section-title{justify-content:space-between;margin-bottom:14px}.section-title h2{margin:0}.metrics{display:grid;grid-template-columns:2fr 1fr 1fr;gap:12px;margin-top:18px}.metrics div{padding:16px;background:var(--bg);border-radius:9px}.metrics span{display:block;color:var(--muted);font-size:12px}.metrics strong{display:block;margin-top:10px;font-size:21px}.daily{display:flex;gap:8px;flex-wrap:wrap;margin-top:16px}.daily span{font-size:12px;padding:8px;background:var(--soft);border-radius:6px}.transfer{margin-top:20px;border-top:1px solid var(--border);padding-top:16px}.file-label{margin:0;display:flex;align-items:center;gap:8px}.file-label input{max-width:200px;font-size:12px}.record{display:flex;align-items:center;gap:10px;padding:13px 0;border-bottom:1px solid var(--border);font-size:13px}.record-content{flex:1;min-width:0;overflow-wrap:anywhere}.record p{margin:5px 0;color:var(--muted);font-size:12px}.record .danger{color:#da5265}footer{padding-top:0;color:var(--muted);font-size:12px}#status{color:var(--accent)}#status[data-error="true"]{color:#d84b5c}dialog{max-width:min(92vw,480px);border:1px solid var(--border);border-radius:12px;padding:24px;background:var(--card);color:var(--fg)}dialog::backdrop{background:#0007}dialog p{line-height:1.8}dialog h2{font-size:18px}@media(prefers-color-scheme:dark){:root{--bg:#171a23;--card:#202530;--fg:#e4e7ef;--muted:#9ba4b8;--border:#343c4e;--accent:#a29bff;--soft:#302d48}button.primary{color:#181626}}@media(max-width:650px){header,main,footer{padding:14px}.columns{grid-template-columns:1fr}.punch{grid-template-columns:1fr}.metrics{grid-template-columns:1fr 1fr}.metrics div:first-child{grid-column:1/-1}.record{flex-wrap:wrap}.record-content{flex-basis:100%}.card{padding:16px}}
2
+
3
+ .today-work{grid-column:1/-1;padding:20px 0;border-top:1px solid var(--border)}.today-work>span{font-size:12px;color:var(--muted)}.today-work strong{display:block;font-size:30px;color:var(--accent);margin:10px 0}.today-work p{font-size:12px;color:var(--muted)}body[data-view="simple"] .complex-only{display:none}body[data-view="simple"] main{max-width:660px;margin:30px auto}body[data-view="simple"] .punch{padding:30px}body[data-view="simple"] .punch .actions{grid-column:1/-1}body[data-view="simple"] .punch .actions button{flex:1;padding:16px;font-size:16px}body[data-view="simple"] .punch>div:first-child{grid-column:1/-1}.settings-drawer{position:fixed;inset:0 0 0 auto;margin:0;width:min(390px,94vw);height:100dvh;max-height:100dvh;max-width:94vw;border-radius:14px 0 0 14px;padding:24px}.settings-drawer form{display:flex;flex-direction:column;gap:16px}.settings-drawer label{margin:0}.settings-drawer select{display:block;width:100%;margin-top:8px}.settings-drawer .hint{margin:0}.settings-drawer [hidden]{display:none}#settings-error{color:#d84b5c;margin:0;font-size:12px}
package/transfer.mjs ADDED
@@ -0,0 +1,29 @@
1
+ import {parseState,statistics,minute} from './model.mjs';
2
+ const xml = value => String(value).replace(/[<>&"']/g, c => ({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;',"'":'&apos;'}[c])).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,'');
3
+ export function workbook(headers, rows) {
4
+ return '<?xml version="1.0" encoding="UTF-8"?><?mso-application progid="Excel.Sheet"?>' + '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"><Worksheet ss:Name="数据"><Table>' + [headers,...rows].map(row => '<Row>'+row.map(cell => '<Cell><Data ss:Type="'+(typeof cell==='number' && Number.isFinite(cell)?'Number':'String')+'">'+xml(cell)+'</Data></Cell>').join('')+'</Row>').join('') + '</Table></Worksheet></Workbook>';
5
+ }
6
+ export const md = value => String(value).replace(/&/g,'&amp;').replace(/\|/g,'\\|').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\r?\n/g,'<br>');
7
+ export function exportRecords(value,format,range) {
8
+ const state=parseState(value);
9
+ if (format==='json') return {name:'打卡-完整备份.json',content:JSON.stringify({kind:'mytools-clock',version:1,state},null,2)};
10
+ const stats=statistics(state,range);
11
+ const rows=state.records.filter(r=>minute(r.start)<range.end && (!r.end || minute(r.end)>range.start)).sort((a,b)=>a.start.localeCompare(b.start)).map(r=>[r.start.replace('T',' '),r.end?.replace('T',' ')||'未下班',r.end?minute(r.end)-minute(r.start):'',r.note]);
12
+ const headers=['上班时间','下班时间','完整记录时长(分钟)','备注'];
13
+ const daily=[['日期','范围内工时(分钟)'],...stats.days.map(d=>[d.date,d.minutes]),['合计',stats.totalMinutes]];
14
+ if(format==='excel') return {name:'打卡-统计.xml',content:workbook(headers,[...rows,[],...daily])};
15
+ if(format!=='md') throw Error('不支持的导出格式');
16
+ const table=items=>items.map(row=>'| '+row.map(md).join(' | ')+' |').join('\n');
17
+ return {name:'打卡-统计.md',content:'# 打卡统计\n\n范围内合计:'+stats.totalMinutes+' 分钟。未完成记录不计入工时。\n\n'+table([daily[0],['---','---'],...daily.slice(1)])+'\n\n## 相交记录(完整时长)\n\n'+table([headers,['---','---','---','---'],...rows])};
18
+ }
19
+ export function readImport(text) {
20
+ if(new TextEncoder().encode(text).length>4*1024*1024) throw Error('导入文件不能超过 4 MB');
21
+ const data=JSON.parse(text);
22
+ if(data?.kind!=='mytools-clock' || data.version!==1 || !data.state) throw Error('请选择“打卡”导出的 JSON 备份');
23
+ return parseState(data.state);
24
+ }
25
+ export function mergeRecords(current,incoming) {
26
+ const next=parseState(current), imported=parseState(incoming);
27
+ const records=new Map(next.records.map(r=>[r.id,r]));imported.records.forEach(r=>records.set(r.id,r));
28
+ next.records=[...records.values()]; return parseState(next);
29
+ }