Files
pages/static/js/task-productivity.js
T
Anya Tokugawa 80d297dab4
Build and publish container images / images (push) Successful in 11m26s
Release container images / release (push) Successful in 20s
feat: atomically capture task mail into Wiki and persist destination defaults
2026-11-06 08:34:29 +09:00

58 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
'use strict';
function mount(root,signal){if(!root||root.dataset.mounted)return;root.dataset.mounted='true';
const ja=document.documentElement.lang.startsWith('ja'), api='/_/api/v1/extension/organizer.tasks/';
const word={tasks:['Tasks','タスク'],report:['Activity report','達成度・作業レポート'],settings:['Task defaults and email','タスクの既定値・メール'],contacts:['Contacts','連絡先'],completed:['Completed','完了件数'],points:['Points','ポイント'],work:['Work hours','作業時間'],focus:['Pomodoro hours','集中時間'],save:['Save','保存'],saved:['Saved','保存しました'],refresh:['Refresh','更新'],project_uuid:['Default project','既定のプロジェクト'],assignee_uuid:['Assignee UUID (annotation only)','担当者UUID(管理用メモ)'],due_days:['Due in days','期限までの日数'],start_days:['Start in days','着手までの日数'],planned_days:['Plan in days','取り組む日までの日数'],review_days:['Review in days','見直しまでの日数'],estimate_minutes:['Estimated minutes','見込み工数(分)'],complexity:['Complexity (1–5)','複雑度(1〜5)'],digest_enabled:['Email daily task list to my account email','毎日のやることリストを自分のメールに送る'],digest_time:['Delivery time','配信時刻'],timezone:['IANA timezone','タイムゾーン(IANA)'],none:['None','なし'],empty:['No records in this period.','この期間の記録はありません。'],partial:['Partial results: narrow the period.','件数上限に達しました。期間を狭めてください。'],error:['Request failed. Input is retained.','処理に失敗しました。入力は保持しています。'],email_required:['Set your account email first.','先にプロフィールにメールアドレスを設定してください。'],smtp_unavailable:['Ask an administrator to configure SMTP.','管理者によるSMTP設定が必要です。']};
const t=k=>(word[k]||[k,k])[ja?1:0],el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
Object.assign(word,{notify_due:['Notify on due dates','期限日に通知する'],notify_planned:['Notify on planned dates','取り組む日に通知する'],reminder_time:['Default notification time','通知の既定時刻']});
Object.assign(word,{wiki_prefix:['Default Wiki parent path for mail','メール本文の既定Wiki親Path']});
const status=root.querySelector('#productivity-status'),content=root.querySelector('#productivity-content');
root.querySelectorAll('[data-word]').forEach(n=>n.textContent=t(n.dataset.word));root.querySelector('h1,h2,h3').textContent=t(root.dataset.view==='settings'?'settings':'report');
async function request(path,options={}){const timeout=AbortSignal.timeout(15000);const r=await fetch(api+path,{credentials:'same-origin',cache:'no-store',signal:signal?AbortSignal.any([signal,timeout]):timeout,...options,headers:{'Content-Type':'application/json',...options.headers}});const d=await r.json().catch(()=>({}));if(!r.ok||r.redirected)throw Error(t(d.error||'error'));return d;}
const error=e=>{status.textContent=e.message||t('error');};
async function settings(){
const data=await request('preferences'),p=data.preferences;const form=el('form');form.className='productivity-settings';const fields={};
const projects=await request('items?kind=project&view=all&limit=100');
if(p.project_uuid&&!projects.items.some(x=>x.uuid===p.project_uuid)){try{const current=await request('items/'+encodeURIComponent(p.project_uuid));if(current.item.kind==='project')projects.items.unshift(current.item);}catch{ /* Keep the saved reference visible without exposing inaccessible data. */ }}
for(const key of ['project_uuid','wiki_prefix','assignee_uuid','due_days','start_days','planned_days','review_days','estimate_minutes','complexity','notify_due','notify_planned','reminder_time','digest_enabled','digest_time','timezone']){
if(key==='notify_due')form.append(el('h3',ja?'新規タスクのInbox通知':'Inbox reminders for new tasks'));
if(key==='digest_enabled')form.append(el('h3',ja?'日次メール':'Daily email'));
const label=el('label',t(key));label.className='productivity-setting';const input=el(key==='project_uuid'?'select':'input');input.name=key;
if(key==='project_uuid'){const empty=el('option',t('none'));empty.value='';input.append(empty);for(const item of projects.items){const option=el('option',item.title);option.value=item.uuid;input.append(option);}if(p[key]&&!projects.items.some(x=>x.uuid===p[key])){const current=el('option',p[key]);current.value=p[key];input.append(current);}}
else if(['digest_enabled','notify_due','notify_planned'].includes(key)){input.type='checkbox';input.checked=!!p[key];input.setAttribute('role','switch');}
else if(key.endsWith('_days')||['estimate_minutes','complexity'].includes(key)){input.type='number';input.min=key==='complexity'?1:0;input.max=key.endsWith('_days')?3650:key==='complexity'?5:10080;input.step=1;}
else input.type=['digest_time','reminder_time'].includes(key)?'time':'text';
if(input.type!=='checkbox')input.value=p[key]??'';if(key==='reminder_time'){input.required=true;input.step=60;}input.disabled=root.dataset.writable!=='true';fields[key]=input;label.append(input);form.append(label);
if(key==='project_uuid')for(const option of input.options)option.defaultSelected=option.selected=option.value===(p.project_uuid||'');
else if(input.type==='checkbox')input.defaultChecked=input.checked;
else input.defaultValue=input.value;
if(key==='wiki_prefix'){input.placeholder='/private/mail';input.maxLength=500;const help=el('p',ja?'メール本文をWikiに保存する親Pathです。空欄ならプロジェクトのWiki配下を使います。保存した本文はそのPathの公開範囲・閲覧権限に従います。':'Parent path for mail Wiki pages. If blank, use the project Wiki subtree. Saved mail inherits the destination path’s visibility and read permissions.');help.className='productivity-note';form.append(help);}
if(key==='reminder_time'){const help=el('p',ja?'新規タスクの対応する日付が設定されている場合だけ通知します。既存タスクは変更しません。通知時刻は保存時のドメインのタイムゾーン('+data.timezone+')を使用します。':'Reminders apply only to new tasks with the corresponding date. Existing tasks are unchanged. Times use the Domain timezone on save ('+data.timezone+').');help.className='productivity-note';form.append(help);}
}
const note=el('p',ja?'日数は作成日からの暦日です。空欄は未設定、0は当日。担当者の指定では閲覧権限は付与されません。メールは今日の計画・期限到来分を最大100件送ります。SMTPは管理者設定を使用し、配信時刻にはキュー待ちの遅延があります。':'Offsets are calendar days from creation; blank means unset, 0 means today. Assignment does not grant access. Email includes up to 100 tasks planned or due today, using administrator SMTP settings. Queue delays may apply.');note.className='productivity-note';form.append(note);
if(data.last_digest){const states={sent:['Sent','送信済み'],sending:['Sending / result pending','送信中・結果未確定'],uncertain:['Delivery uncertain (no automatic retry)','結果不明(自動再送なし)'],cancelled:['Cancelled','送信取消']};form.append(el('p',(ja?'直近の配信: ':'Latest delivery: ')+data.last_digest.day+' · '+(states[data.last_digest.state]||['Unknown','不明'])[ja?1:0]));}
const save=el('button',t('save'));save.type='submit';save.disabled=root.dataset.writable!=='true';form.append(save);content.replaceChildren(form);
fields.project_uuid.value=p.project_uuid||'';
form.onsubmit=async event=>{event.preventDefault();if(!form.reportValidity())return;save.disabled=true;const value={...p};for(const [key,input] of Object.entries(fields)){value[key]=input.type==='checkbox'?input.checked:input.type==='number'?(input.value===''?null:Number(input.value)):input.value;}try{const result=await request('preferences',{method:'PUT',body:JSON.stringify(value)});Object.assign(p,result.preferences);status.textContent=t('saved');}catch(e){error(e);}finally{save.disabled=false;}};
}
function taskTable(data){const wrap=el('div');wrap.className='productivity-table-wrap';const table=el('table');table.className='productivity-table';const head=el('tr');for(const name of [ja?'タスク':'Task',t('points'),t('work')])head.append(el('th',name));const thead=el('thead');thead.append(head);table.append(thead);const body=el('tbody');for(const task of data.tasks){const row=el('tr'),name=el('td'),link=el('a',(task.completed?'✓ ':'')+(task.title||task.uuid));link.href='/v/plan/task/'+encodeURIComponent(task.uuid);name.append(link);row.append(name,el('td',String(task.points||0)),el('td',(task.work_ms/3600000).toFixed(2)));body.append(row);}table.append(body);wrap.append(table);if(!data.tasks.length)wrap.append(el('p',t('empty')));return wrap;}
async function report(){
const controls=el('form');controls.className='productivity-controls';const from=el('input'),to=el('input');from.type=to.type='date';from.required=to.required=true;from.ariaLabel=ja?'開始日':'From';to.ariaLabel=ja?'終了日(含まない)':'To (exclusive)';const refresh=el('button','↻ '+t('refresh'));controls.append(from,to,refresh);
const results=el('section');content.replaceChildren(controls,results);let generation=0;
async function load(){const ticket=++generation;refresh.disabled=true;try{const query=new URLSearchParams();if(from.value)query.set('from',from.value);if(to.value)query.set('to',to.value);const d=await request('report?'+query);if(ticket!==generation)return;status.textContent=d.partial?t('partial'):d.timezone;
if(!from.value&&d.days.length){from.value=d.days[0].date;const end=new Date(d.days.at(-1).date+'T12:00:00Z');end.setUTCDate(end.getUTCDate()+1);to.value=end.toISOString().slice(0,10);}
const stats=el('div');stats.className='productivity-stats';for(const [label,key,divisor] of [['completed','completed',1],['points','points',1],['work','work_ms',3600000],['focus','focus_ms',3600000]]){const card=el('div',t(label));card.className='productivity-stat';const sum=d.days.reduce((total,day)=>total+day[key],0)/divisor;card.append(el('strong',divisor===1?String(sum):sum.toFixed(2)));stats.append(card);}
const scroll=el('div');scroll.className='productivity-heatmap-scroll';const grid=el('div');grid.className='productivity-heatmap';grid.ariaLabel=t('report');const detail=el('section');detail.append(taskTable(d));let detailSequence=0;
if(d.days.length){const weekday=new Date(d.days[0].date+'T12:00:00Z').getUTCDay();for(let i=0;i<weekday;i++)grid.append(el('span'));}
for(const day of d.days){const cell=el('button');cell.type='button';cell.className='productivity-day';cell.dataset.level=String(day.points===0?0:day.points<=3?1:day.points<=8?2:day.points<=20?3:4);cell.title=cell.ariaLabel=`${day.date}: ${day.completed} ${t('completed')}, ${day.points} ${t('points')}, ${(day.work_ms/3600000).toFixed(2)}h`;
cell.onclick=async()=>{const sequence=++detailSequence;try{const next=new Date(day.date+'T12:00:00Z');next.setUTCDate(next.getUTCDate()+1);const single=await request('report?'+new URLSearchParams({from:day.date,to:next.toISOString().slice(0,10)}));if(sequence!==detailSequence)return;detail.replaceChildren(el('h2',day.date),taskTable(single));}catch(e){error(e);}};grid.append(cell);}
scroll.append(grid);const note=el('p',ja?'1タスクのポイント = 1 + ⌈見積分数 / 30⌉ × 複雑度(1〜5)。完了取消は集計から除外。作業時間とPomodoroは別集計で、重複する場合は加算しません。':'Points per task = 1 + ceil(estimated minutes / 30) × complexity (1–5). Reopened tasks are excluded. Work and Pomodoro are separate; overlapping time is not added together.');note.className='productivity-note';results.replaceChildren(stats,scroll,note,detail);
}catch(e){error(e);}finally{refresh.disabled=false;}}
controls.onsubmit=e=>{e.preventDefault();load();};await load();
}
return (root.dataset.view==='settings'?settings():report()).catch(error);
}
window.PagesWikiProductivityMount=mount;
mount(document.getElementById('task-productivity'));
})();