Initial team BPM workspace with managed connections, scanning and mail templates
This commit is contained in:
commit
34770ed338
101 files changed
+6499
No files matched your search
@@ -0,0 +1,46 @@
|
||||
// Self-contained function: injected only after the user clicks Export.
|
||||
function captureOrder() {
|
||||
const source = document.querySelector('form');
|
||||
if (!source) throw new Error('当前页面没有订单表单,请进入 BPM 订单详情。');
|
||||
const bindings = { order:'OFR_WY_Applicant.OrderNum', project:'OFR_WY_BInfo.ProductNum', model:'OFR_WY_BInfo.ProductModelNEW', serial:'OFR_WY_Applicant.SN' };
|
||||
const labels = { order:'订单号', project:'项目编号', model:'产品型号', serial:'通知书编号' };
|
||||
const metadata = {};
|
||||
for (const [key, binding] of Object.entries(bindings)) {
|
||||
const el = source.querySelector(`[xdatabind="${binding}"]`);
|
||||
metadata[key] = (el?.value ?? el?.textContent ?? '').trim();
|
||||
}
|
||||
const clone = source.cloneNode(true);
|
||||
const originals = [source, ...source.querySelectorAll('*')];
|
||||
const copies = [clone, ...clone.querySelectorAll('*')];
|
||||
for (let index = originals.length - 1; index >= 0; index--) {
|
||||
const original = originals[index], copy = copies[index];
|
||||
const style = getComputedStyle(original);
|
||||
const type = (original.getAttribute('type') || '').toLowerCase();
|
||||
const tag = original.tagName.toLowerCase();
|
||||
if (['script','iframe','object','embed','button','link','meta'].includes(tag) || ['hidden','password','button','submit','reset','file'].includes(type) || style.display === 'none' || style.visibility === 'hidden' || original.hidden || original.getAttribute('printout') === 'false') {
|
||||
copy.remove(); continue;
|
||||
}
|
||||
if (['input','textarea','select'].includes(tag)) {
|
||||
const span = document.createElement('span');
|
||||
span.className = original.className;
|
||||
span.style.cssText = 'display:inline-block;max-width:100%;white-space:pre-wrap;overflow-wrap:break-word;min-height:1em;';
|
||||
span.textContent = ['checkbox','radio'].includes(type) ? (original.checked ? '☑' : '☐') : tag === 'select' ? [...original.selectedOptions].map(option => option.textContent).join('、') : original.value;
|
||||
copy.replaceWith(span);
|
||||
} else {
|
||||
for (const attribute of [...copy.attributes]) {
|
||||
if (/^on/i.test(attribute.name) || ['action','srcdoc','srcset','formaction','value'].includes(attribute.name.toLowerCase())) copy.removeAttribute(attribute.name);
|
||||
}
|
||||
if (tag === 'img') copy.setAttribute('src', original.src);
|
||||
}
|
||||
}
|
||||
for (const id of ['taskCommentForm','TaskCommentCount']) {
|
||||
const el = clone.querySelector('#'+id);
|
||||
if (el) el.remove();
|
||||
}
|
||||
const styles = [...document.querySelectorAll('style')].map(el => el.textContent);
|
||||
const stylesheetUrls = [...document.querySelectorAll('link[rel="stylesheet"][href]')].map(el => el.href);
|
||||
const styleSources = [...document.querySelectorAll('style,link[rel="stylesheet"][href]')].map(el => el.tagName.toLowerCase() === 'style' ? {text:el.textContent} : {url:el.href});
|
||||
const imageUrls = [...clone.querySelectorAll('img[src]')].map(el => el.getAttribute('src'));
|
||||
return { metadata, html:clone.outerHTML, styles, styleSources, stylesheetUrls, imageUrls:[...new Set(imageUrls)], width:1264, missing:Object.keys(bindings).filter(key => !metadata[key]).map(key => labels[key]), warnings:[] };
|
||||
}
|
||||
if (typeof module !== 'undefined') module.exports = { captureOrder };
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "订单通知书 PDF",
|
||||
"version": "0.1.0",
|
||||
"description": "将当前已登录的 BPM 订单页面导出为自动命名的本地 PDF。",
|
||||
"permissions": ["activeTab", "scripting", "storage"],
|
||||
"host_permissions": ["https://bpm.skyworthdigital.com/*", "http://127.0.0.1/*"],
|
||||
"background": { "service_worker": "worker.js" },
|
||||
"action": { "default_popup": "popup.html", "default_title": "导出订单通知书" }
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
*{box-sizing:border-box}body{margin:0;width:360px;padding:24px;background:#f6f7f5;color:#1e302b;font:14px/1.6 "Microsoft YaHei",sans-serif}.eyebrow{color:#557269;font-size:11px;letter-spacing:1px}h1{font-size:24px;line-height:1.4;margin:7px 0 12px}.intro{color:#52665e;margin:0 0 22px}button{width:100%;border:0;border-radius:8px;background:#17684f;color:white;padding:12px;font:600 14px "Microsoft YaHei",sans-serif;cursor:pointer}button:hover{background:#10563f}button:disabled{opacity:.65;cursor:wait}section{margin-top:20px;padding:14px;background:white;border:1px solid #dce4df;border-radius:8px;overflow-wrap:anywhere}.label{font-size:11px;color:#698075}section p{margin:6px 0 0;white-space:pre-wrap}.error{color:#a73d2b}.success{color:#13765b}.hint{font-size:11px;color:#6b7c74;margin:16px 0 0}
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head><meta charset="utf-8"><title>订单通知书</title><link rel="stylesheet" href="popup.css"></head>
|
||||
<body>
|
||||
<div class="eyebrow">BPM · 本地归档</div>
|
||||
<h1>订单通知书</h1>
|
||||
<p class="intro">将当前订单页面保存为 PDF,自动按订单和项目命名。</p>
|
||||
<button id="export">导出当前订单</button>
|
||||
<section id="status" aria-live="polite"><span class="label">使用方式</span><p>先启动本地工具,再打开已登录的订单详情页。</p></section>
|
||||
<p class="hint">导出在后台继续,可关闭此面板。文件保存在本地输出目录。</p>
|
||||
<script src="popup.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,23 @@
|
||||
const button = document.querySelector('#export');
|
||||
const status = document.querySelector('#status');
|
||||
function show(value) {
|
||||
if (!value) return;
|
||||
button.disabled = value.status === 'running';
|
||||
status.replaceChildren();
|
||||
const label = document.createElement('span'); label.className='label'; label.textContent=value.status==='success'?'导出完成':value.status==='error'?'需要处理':'导出进度';
|
||||
const text = document.createElement('p'); text.className=value.status; text.textContent=value.message;
|
||||
if (value.filename) text.textContent+='\n'+value.filename+'\n'+value.path;
|
||||
if (value.warnings?.length) text.textContent+='\n\n'+value.warnings.join('\n');
|
||||
status.append(label,text);
|
||||
}
|
||||
chrome.storage.session.get('lastExport').then(data=>show(data.lastExport));
|
||||
chrome.runtime.sendMessage({type:'status'}).then(result=>{if(result.ok)show(result.value);},error=>show({status:'error',message:error.message}));
|
||||
chrome.storage.onChanged.addListener((changes,area)=>{if(area==='session' && changes.lastExport)show(changes.lastExport.newValue);});
|
||||
button.addEventListener('click',async()=>{
|
||||
button.disabled=true;
|
||||
try {
|
||||
const [tab] = await chrome.tabs.query({active:true,currentWindow:true});
|
||||
const result = await chrome.runtime.sendMessage({type:'export',tabId:tab.id});
|
||||
if (!result.ok) show({status:'error',message:result.error});
|
||||
} catch(error) {show({status:'error',message:error.message});}
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
importScripts('local-config.js', 'capture.js');
|
||||
const config = globalThis.ORDER_LOCAL_CONFIG;
|
||||
const state = value => chrome.storage.session.set({ lastExport:value });
|
||||
let running = false;
|
||||
|
||||
async function requestLocal(route, body) {
|
||||
const response = await fetch(config.endpoint + route, {
|
||||
method: body ? 'POST' : 'GET',
|
||||
headers: { 'Content-Type':'application/json', 'X-Order-Token':config.token },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
signal: AbortSignal.timeout(10000)
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.error || '本地导出服务返回错误。');
|
||||
return result;
|
||||
}
|
||||
|
||||
async function collectAssets(snapshot) {
|
||||
const allowed = 'https://bpm.skyworthdigital.com';
|
||||
snapshot.images = [];
|
||||
const jobs = [
|
||||
...[...new Set(snapshot.stylesheetUrls || [])].map(url => ({url,kind:'css'})),
|
||||
...(snapshot.imageUrls || []).map(url => ({url,kind:'image'}))
|
||||
];
|
||||
if (jobs.length > 100) throw new Error('页面资源过多,请确认当前标签页是单个订单详情。');
|
||||
let total = 0;
|
||||
const collected = await Promise.all(jobs.map(async ({url,kind}) => {
|
||||
try {
|
||||
if (kind === 'image' && /^data:image\/(png|jpeg|gif|webp);base64,/i.test(url)) { snapshot.images.push({url,data:url}); return; }
|
||||
if (new URL(url).origin !== allowed) throw new Error('不属于 BPM 站点');
|
||||
const response = await fetch(url,{credentials:'include',redirect:'error',signal:AbortSignal.timeout(15000)});
|
||||
if (!response.ok) throw new Error('读取失败');
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
total += bytes.length;
|
||||
if (bytes.length > 3*1024*1024 || total > 12*1024*1024) throw new Error('资源超过大小限制');
|
||||
const mime = (response.headers.get('content-type') || '').split(';')[0];
|
||||
if (kind === 'css') {
|
||||
if (!/text\/css/i.test(mime)) throw new Error('样式资源格式不匹配');
|
||||
return {url,css:new TextDecoder('utf-8').decode(bytes)};
|
||||
} else {
|
||||
if (!/^image\/(png|jpeg|gif|webp)$/i.test(mime)) throw new Error('图片格式暂不支持');
|
||||
let binary = '';
|
||||
for (let i=0;i<bytes.length;i+=32768) binary += String.fromCharCode(...bytes.subarray(i,i+32768));
|
||||
snapshot.images.push({url,data:`data:${mime};base64,${btoa(binary)}`});
|
||||
}
|
||||
} catch {
|
||||
snapshot.warnings.push(kind === 'css' ? '有一项页面样式未能嵌入,请核对输出排版。' : '有一张图片未能嵌入,请核对图片区域。');
|
||||
}
|
||||
}));
|
||||
const cssByUrl = new Map(collected.filter(Boolean).map(item=>[item.url,item.css]));
|
||||
snapshot.styles = snapshot.styleSources ? snapshot.styleSources.map(item=>item.url ? cssByUrl.get(item.url) || '' : item.text || '') : [
|
||||
...(snapshot.stylesheetUrls || []).map(url=>cssByUrl.get(url) || ''), ...snapshot.styles
|
||||
];
|
||||
delete snapshot.styleSources;
|
||||
delete snapshot.stylesheetUrls;
|
||||
delete snapshot.imageUrls;
|
||||
snapshot.warnings = [...new Set(snapshot.warnings)];
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
async function exportTab(tabId) {
|
||||
if (running) throw new Error('正在导出,请稍候。');
|
||||
running = true;
|
||||
try {
|
||||
await state({status:'running',message:'正在连接本地工具…'});
|
||||
await requestLocal('/health');
|
||||
const tab = await chrome.tabs.get(tabId);
|
||||
if (!tab.url || new URL(tab.url).origin !== 'https://bpm.skyworthdigital.com') throw new Error('请先切换到 BPM 订单详情标签页。');
|
||||
const results = await chrome.scripting.executeScript({target:{tabId},func:captureOrder});
|
||||
const snapshot = results[0]?.result;
|
||||
if (!snapshot) throw new Error('未采集到订单页面,请刷新订单后再试。');
|
||||
if (snapshot.missing.length) throw new Error('缺少'+snapshot.missing.join('、')+'。请检查是否进入正确的订单详情页。');
|
||||
await state({status:'running',message:'正在生成 '+snapshot.metadata.order+' 的 PDF…'});
|
||||
const accepted = await requestLocal('/export', await collectAssets(snapshot));
|
||||
await state({status:'running',jobId:accepted.jobId,message:'正在排版 '+snapshot.metadata.order+' 的 PDF…'});
|
||||
let result;
|
||||
const deadline=Date.now()+120000;
|
||||
while (Date.now()<deadline) {
|
||||
result=await requestLocal('/jobs/'+accepted.jobId);
|
||||
if (result.status!=='running') break;
|
||||
await new Promise(resolve=>setTimeout(resolve,750));
|
||||
}
|
||||
if (!result || result.status==='running') throw new Error('排版用时较长,请检查输出目录,稍后重试。');
|
||||
if (result.status==='error') throw new Error(result.error);
|
||||
await state({status:'success',message:'已保存',...result});
|
||||
await chrome.action.setBadgeText({text:'✓'});
|
||||
await chrome.action.setBadgeBackgroundColor({color:'#13765b'});
|
||||
return result;
|
||||
} catch(error) {
|
||||
const message = /Failed to fetch|fetch failed|NetworkError/i.test(error.message) ? '无法连接本地工具。请先双击“启动工具.cmd”,保持窗口运行。' : error.message;
|
||||
await state({status:'error',message});
|
||||
await chrome.action.setBadgeText({text:'!'});
|
||||
await chrome.action.setBadgeBackgroundColor({color:'#b44334'});
|
||||
throw new Error(message);
|
||||
} finally { running = false; }
|
||||
}
|
||||
|
||||
async function currentState() {
|
||||
let value=(await chrome.storage.session.get('lastExport')).lastExport;
|
||||
if (value?.status==='running' && !running) {
|
||||
try {
|
||||
if (!value.jobId) throw new Error('上次采集被中断,请检查输出目录后重试。');
|
||||
const job=await requestLocal('/jobs/'+value.jobId);
|
||||
if (job.status==='success') value={...job,message:'已保存'};
|
||||
else if (job.status==='error') value={status:'error',message:job.error};
|
||||
} catch(error) {value={status:'error',message:error.message};}
|
||||
await state(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
chrome.runtime.onMessage.addListener((message,sender,sendResponse) => {
|
||||
if (sender.id !== chrome.runtime.id) return;
|
||||
if (message.type==='status') {currentState().then(value=>sendResponse({ok:true,value}),error=>sendResponse({ok:false,error:error.message}));return true;}
|
||||
if (message.type !== 'export') return;
|
||||
exportTab(message.tabId).then(result=>sendResponse({ok:true,result}),error=>sendResponse({ok:false,error:error.message}));
|
||||
return true;
|
||||
});
|
||||
Reference in new issue
Block a user