MarketingSystemDataTool/web/main.js

58 lines
2.5 KiB
JavaScript

async function loadTemplates(){
const res=await fetch('/api/templates');
const data=await res.json();
const el=document.getElementById('templates');
const rows=data.map(t=>`<tr><td>${t.id}</td><td>${t.name}</td><td>${t.datasource}</td><td>${t.file_format}</td><td>${t.explain_score||''}</td><td><button data-id="${t.id}" class="btn btn-primary btn-sm export">执行导出</button></td></tr>`).join('');
el.innerHTML=`<table class="table table-striped table-sm"><thead><tr><th>ID</th><th>名称</th><th>数据源</th><th>格式</th><th>EXPLAIN评分</th><th>操作</th></tr></thead><tbody>${rows}</tbody></table>`;
document.querySelectorAll('button.export').forEach(b=>b.onclick=async()=>{
const id=b.getAttribute('data-id');
const payload={template_id:Number(id),requested_by:1,permission:{},options:{},file_format:'csv'};
const r=await fetch('/api/exports',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
const j=await r.json();
loadJob(j.id);
});
}
async function loadJob(id){
const res=await fetch('/api/exports/'+id);
const j=await res.json();
const el=document.getElementById('jobs');
const link=j.files&&j.files.length?`<a class="btn btn-success btn-sm" href="/api/exports/${id}/download" target="_blank">下载</a>`:'';
el.innerHTML=`<div class="alert alert-info">任务 ${id} 状态:<strong>${j.status}</strong> 行数:${j.total_rows||''} ${link}</div>`;
}
document.getElementById('tpl-form').onsubmit=async(e)=>{
e.preventDefault();
const fd=new FormData(e.target);
const fields=fd.get('fields').split(',').map(s=>s.trim());
const filters={};
const creators=fd.get('creator_in');
if(creators){filters.creator_in=creators.split(',').map(s=>Number(s.trim()))}
const tb=fd.get('time_begin');
const te=fd.get('time_end');
if(tb&&te){
const fmt=(s)=>s.replace('T',' ')+':00';
filters.create_time_between=[fmt(tb),fmt(te)]
}
const payload={
name:fd.get('name'),
datasource:fd.get('datasource'),
main_table:fd.get('main_table'),
fields,
filters,
file_format:fd.get('file_format'),
owner_id:Number(fd.get('owner_id')),
visibility:fd.get('visibility')
};
const res=await fetch('/api/templates',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
if(res.ok){
loadTemplates();
} else {
const t=await res.text();
const el=document.getElementById('templates');
el.insertAdjacentHTML('afterbegin',`<div class="alert alert-danger">${t}</div>`);
}
};
loadTemplates();