import {watchPreview} from './lifecycle.js'; const $=id=>document.getElementById(id); let session,state,busy=false,lastResult=null,pdfFile=null,pdfResult=null,pdfPage=0,history=[],calculated=false; const descriptions={erp:['采购报价与审批','填写采购信息,计算含税金额并查看审批级别。','采购信息'],calculator:['工程计算器','支持括号、小数和连续运算,可回填历史记录。','表达式与键盘'],pdf:['PDF 文档解析','上传文字 PDF,逐页阅读并导出文本。也可以载入两页示例。','文件与解析'],webapp:['网页应用','根据本次需求生成的应用。','应用'],'business-app':['业务应用','根据本次需求生成的业务应用。','应用'],'erp-orders':['采购订单清单','本地模拟数据 · 付款仅更新演示记录,不发起真实转账。','订单']}; const errors={INVALID_INPUT:'输入不符合接口要求,请核对字段和格式。',INVALID_EXPRESSION:'表达式不完整或包含非法字符,请检查数字、运算符和括号。',DIVISION_BY_ZERO:'除数不能为零,请修改表达式。',LIMIT_EXCEEDED:'表达式超出长度、层数或数值范围。',FORBIDDEN:'当前演示用户只允许处理 sales 部门的业务。',INVALID_PDF:'文件不是有效的 PDF,或内容已经损坏。',ENCRYPTED_PDF:'此文件已加密;请提供获准使用的未加密 PDF。',PAGE_LIMIT:'PDF 超过 20 页,请选择更小的文件。',PDF_TOO_LARGE:'文件超过 128 KiB,请选择较小的 PDF。',TEXT_LIMIT:'提取文本超过本次演示上限,请缩减文档。'}; function notice(text,error=false){$('notice').textContent=text;$('notice').classList.toggle('error',error);} function installBusinessBridge(frame){ const pending=new Set(); addEventListener('message',async event=>{ const data=event.data;if(event.source!==frame.contentWindow||event.origin!=='null'||!data||data.type!=='zk-business-request')return; if(typeof data.id!=='string'||!/^request-[0-9]{1,12}$/.test(data.id)||pending.has(data.id)||pending.size>=8)return; const reply=(ok,body,error)=>event.source.postMessage({type:'zk-business-response',id:data.id,ok,body,error},'*'); if(!['GET','POST'].includes(data.method)||typeof data.path!=='string'||!/^\/(?:[A-Za-z0-9_/?=&.+-]|%[0-9A-Fa-f]{2}){0,500}$/.test(data.path)){ reply(false,null,'请求格式无效');return; } const path=data.path.split('?')[0]; if(!((data.method==='GET'&&['/api/app/list','/api/app/meta'].includes(path))||(data.method==='POST'&&path==='/api/app/action'))){ reply(false,null,'该操作不可用');return; } pending.add(data.id); try{const result=await api('/api/preview/request',{method:data.method,path:data.path,preview_id:state.id}); if(result.status>=200&&result.status<300)reply(true,result.body,null); else reply(false,null,'操作未完成:'+String(result.body?.error||result.status).slice(0,80)); }catch(error){reply(false,null,error.message||'操作未完成');}finally{pending.delete(data.id);} }); } async function api(path,body){const r=await fetch(path,{method:body===undefined?'GET':'POST',credentials:'same-origin',headers:{'Content-Type':'application/json',...(session?{'X-CSRF-Token':session.csrf}:{})},...(body===undefined?{}:{body:JSON.stringify(body)})});const result=await r.json();if(!r.ok)throw Error(result.message||'服务暂未返回,请返回工作台查看当前运行状态。');return result;} function setBusy(value){busy=value;document.querySelectorAll('#inputs button,#inputs input').forEach(b=>b.disabled=value);} async function invoke(path,method='GET',body){if(busy)return null;setBusy(true);notice('正在处理…');try{const r=await api('/api/preview/request',{method,path,preview_id:state.id,...(body===undefined?{}:{body})});if(r.status!==200)throw Error(errors[r.body?.error]||'暂时无法完成,请检查输入后重试。');notice('处理完成。');return r.body;}catch(e){notice(e.message,true);return null;}finally{setBusy(false);}} function row(label,value){const div=document.createElement('div');div.className='result-row';const a=document.createElement('span'),b=document.createElement('strong');a.textContent=label;b.textContent=value;div.append(a,b);return div;} function metric(value,unit=''){const d=document.createElement('div');d.className='metric';d.textContent=value;if(unit){const s=document.createElement('small');s.textContent=' '+unit;d.append(s);}return d;} function download(name,value,type='text/plain;charset=utf-8'){const a=document.createElement('a'),url=URL.createObjectURL(new Blob([value],{type}));a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} async function copy(text){try{await navigator.clipboard.writeText(text);notice('已复制。');}catch{notice('请选中结果文本复制。');}} function erp(){ $('inputs').innerHTML='

当前账号属于 sales 部门。1万元以下自主审批,1万至10万元由部门经理审批,10万元起由总监审批。

'; const clearQuote=()=>{lastResult=null;$('result').replaceChildren();}; for(const id of ['quantity','price','department'])$(id).oninput=()=>{clearQuote();notice('输入已变更,请重新计算报价。');}; $('resetErp').onclick=()=>{$('quantity').value='3';$('price').value='125.50';$('department').value='sales';clearQuote();notice('已恢复示例,点击计算报价。');}; $('erpForm').onsubmit=async e=>{e.preventDefault();const q=new URLSearchParams({quantity:$('quantity').value,unitPrice:$('price').value,department:$('department').value});const result=await invoke('/api/purchase/quote?'+q);if(!result)return;lastResult=result;$('result').replaceChildren(metric(result.total,'元'),row('所属部门',result.department),row('审批级别',{SELF:'采购员自主审批',MANAGER:'部门经理审批',DIRECTOR:'总监审批'}[result.approval]||result.approval));}; } function orders(){ const workspace=$('workspace');workspace.classList.add('orders-layout'); workspace.innerHTML='

1000 条模拟订单,数据保存在本次预览的本地文件中;关闭预览后数据会重置。

正在载入订单…

采购订单号采购订单名称供应商信息采购产品信息采购数量入库 / 退货订单金额已付款操作

'; let page=1,filter='all',query='',total=0,active=null,working=false; const money=c=>(Math.floor(c/100)+'.'+String(c%100).padStart(2,'0')); const message=(text,error=false)=>{$('orderNotice').textContent=text;$('orderNotice').classList.toggle('error',error);}; async function call(path,method='GET'){ const result=await api('/api/preview/request',{method,path,preview_id:state.id}); if(result.status!==200){const code=result.body?.error;throw Error({LIMIT_EXCEEDED:'超过可入库、可退货或可付款的上限。',INVALID_INPUT:'输入不符合要求,请检查后重试。',NOT_FOUND:'订单不存在。',UNAUTHORIZED:'演示会话不可用,请重新打开。'}[code]||'操作未完成,请检查输入后重试。');} return result.body; } function cell(row,value){const td=document.createElement('td');td.textContent=String(value);row.append(td);return td;} async function load(){ if(working)return;working=true;message('正在读取订单…'); try{ const params=new URLSearchParams({page:String(page),query,filter}); const result=await call('/api/orders?'+params);total=result.total; const rows=$('orderRows');rows.replaceChildren(); for(const item of result.orders){ const tr=document.createElement('tr');cell(tr,item.id);cell(tr,item.name);cell(tr,item.supplier);cell(tr,item.product);cell(tr,item.quantity); cell(tr,`${item.received} / ${item.returned}`);cell(tr,'¥'+money(item.totalCents));cell(tr,'¥'+money(item.paidCents)); const actions=cell(tr,'');actions.className='order-actions'; for(const [kind,label] of [['receive','入库'],['return','采购退货'],['pay','付款']]){ const button=document.createElement('button');button.type='button';button.textContent=label;button.className='order-action '+kind; button.setAttribute('aria-label',`${item.id} ${label}`);button.onclick=()=>openAction(item,kind,label);actions.append(button); } rows.append(tr); } $('orderCount').textContent=`共 ${total} 条`;const pages=Math.max(1,Math.ceil(total/20));$('orderPage').textContent=`第 ${page} / ${pages} 页`; $('orderPrev').disabled=page<=1;$('orderNext').disabled=page>=pages; message(total?'订单已载入。':'没有匹配的订单。'); }catch(e){message(e.message,true);}finally{working=false;} } function openAction(item,kind,label){ active={item,kind};$('orderActionTitle').textContent=`${label} · ${item.id}`; $('orderActionLabel').textContent=kind==='pay'?'付款金额(元)':'数量(件)'; $('orderActionHint').textContent=kind==='receive'?`最多可入库 ${item.quantity-item.received} 件。`:kind==='return'?`最多可退货 ${item.received-item.returned} 件。`:`最多可付款 ¥${money(item.totalCents-item.paidCents)}。`; $('orderActionValue').value='';$('orderActionError').textContent='';$('orderDialog').showModal();$('orderActionValue').focus(); } $('orderActionForm').onsubmit=async e=>{ e.preventDefault();if(working||!active)return; const value=$('orderActionValue').value.trim(),pay=active.kind==='pay'; if(!(pay?/^\d{1,7}(?:\.\d{1,2})?$/:/^\d{1,6}$/).test(value)){$('orderActionError').textContent=pay?'请输入最多两位小数的金额。':'请输入正整数数量。';return;} const parts=value.split('.'),number=pay?Number(parts[0])*100+Number((parts[1]||'').padEnd(2,'0')):Number(value); if(!Number.isSafeInteger(number)||number<=0){$('orderActionError').textContent='请输入大于零的数值。';return;} const params=new URLSearchParams({id:active.item.id,[pay?'cents':'quantity']:String(number)}); working=true;$('orderActionForm').querySelector('button[type=submit]').disabled=true; try{await call(`/api/orders/${active.kind}?${params}`,'POST');$('orderDialog').close();working=false;await load();message('操作成功,订单已更新。');} catch(err){$('orderActionError').textContent=err.message;} finally{working=false;$('orderActionForm').querySelector('button[type=submit]').disabled=false;} }; $('orderCancel').onclick=()=>$('orderDialog').close(); $('orderSearch').onsubmit=e=>{e.preventDefault();const input=$('orderQuery').value.trim();if(!/^[A-Za-z0-9_-]{0,60}$/.test(input)){message('请使用订单号、供应商或产品的英文模拟标识查询。',true);return;}query=input;page=1;load();}; for(const [id,value] of [['orderAll','all'],['orderPending','pending']])$(id).onclick=()=>{filter=value;page=1;$('orderAll').classList.toggle('active',value==='all');$('orderPending').classList.toggle('active',value==='pending');load();}; $('orderPrev').onclick=()=>{if(page>1){page--;load();}};$('orderNext').onclick=()=>{if(page{lastResult=null;calculated=false;$('result').replaceChildren();$('copyResult').disabled=true;}; const keys=['C','⌫','(',')','7','8','9','/','4','5','6','*','1','2','3','-','0','.','=','+']; for(const key of keys){const b=document.createElement('button');b.type='button';b.textContent=key;b.setAttribute('aria-label',{'C':'清空','⌫':'退格','=':'计算'}[key]||key);b.onclick=()=>{const input=$('expression');if(key==='='){$('calcForm').requestSubmit();return;}if(key==='C'){input.value='';notice('已清空表达式。');}else if(key==='⌫'){input.value=input.value.slice(0,-1);}else{if(calculated)input.value=/^[+*/-]$/.test(key)&&lastResult?lastResult.result:'';if(input.value.length<128)input.value+=key;}invalidate();input.focus();};$('keypad').append(b);} $('expression').oninput=()=>{invalidate();notice('输入已变更,请重新计算。');}; $('expression').onkeydown=e=>{if(e.key==='Escape'){e.preventDefault();$('expression').value='';invalidate();notice('已清空表达式。');}}; $('calcForm').onsubmit=async e=>{e.preventDefault();const expression=$('expression').value;invalidate();const result=await invoke('/api/calculate?expression64='+encode(expression));if(!result){$('copyResult').disabled=true;return;}lastResult=result;calculated=true;$('copyResult').disabled=false;$('result').replaceChildren(row('表达式',result.expression),metric(result.result));history.unshift(result);history=history.slice(0,10);$('history').replaceChildren();for(const h of history){const li=document.createElement('li'),b=document.createElement('button');b.type='button';b.textContent=`${h.expression} = ${h.result}`;b.onclick=()=>{$('expression').value=h.expression;invalidate();notice('已回填历史表达式,点击计算后再执行。');};li.append(b);$('history').append(li);}}; $('copyResult').disabled=true;$('copyResult').onclick=()=>lastResult?copy(lastResult.result):notice('请先计算一个结果。'); } function clearPdf(){pdfResult=null;pdfPage=0;$('result').replaceChildren();} function pdf(){ $('inputs').innerHTML='

尚未选择文件。最大 128 KiB,最多 20 页。

支持文字 PDF;扫描件需先经过文字识别。

'; const choose=file=>{if(busy)return;pdfFile=file||null;clearPdf();$('fileInfo').textContent=pdfFile?`${pdfFile.name} · ${pdfFile.size} 字节`:'尚未选择文件。最大 128 KiB,最多 20 页。';notice(pdfFile?'文件已选择,点击开始解析。':'请先选择文件或载入两页示例。');}; $('pdfFile').onchange=()=>choose($('pdfFile').files[0]); $('clearPdf').onclick=()=>{$('pdfFile').value='';choose(null);}; $('pdfDrop').ondragover=e=>{e.preventDefault();if(!busy)$('pdfDrop').classList.add('dragging');}; $('pdfDrop').ondragleave=()=>$('pdfDrop').classList.remove('dragging'); $('pdfDrop').ondrop=e=>{e.preventDefault();$('pdfDrop').classList.remove('dragging');if(busy)return;if(e.dataTransfer.files.length!==1){notice('每次请选择一个 PDF 文件。',true);return;}$('pdfFile').value='';choose(e.dataTransfer.files[0]);}; $('samplePdf').onclick=async()=>{if(busy)return;setBusy(true);try{const r=await fetch('/api/preview/pdf-sample?preview_id='+encodeURIComponent(state.id),{credentials:'same-origin'});if(!r.ok)throw Error('示例载入失败,请稍后重试。');pdfFile=new File([await r.blob()],'two-page-example.pdf',{type:'application/pdf'});$('pdfFile').value='';clearPdf();$('fileInfo').textContent=`${pdfFile.name} · ${pdfFile.size} 字节`;notice('两页示例已载入,点击开始解析。');}catch(e){notice(e.message,true);}finally{setBusy(false);}}; $('parsePdf').onclick=async()=>{try{if(!pdfFile){notice('请先选择文件或载入两页示例。',true);return;}if(pdfFile.size>131072){notice(errors.PDF_TOO_LARGE,true);return;}const selected=pdfFile;const bytes=new Uint8Array(await selected.arrayBuffer());if(pdfFile!==selected)return;let text='';for(let i=0;i=result.pageCount-1;prev.onclick=()=>{pdfPage--;renderPdf();};next.onclick=()=>{pdfPage++;renderPdf();};pager.append(prev,label,next);const pre=document.createElement('pre');pre.className='pdf-text';pre.textContent=result.pages[pdfPage]?.text||'本页没有可提取的文字。';const actions=document.createElement('div');actions.className='actions';for(const [label,action] of [['复制本页',()=>copy(result.pages[pdfPage]?.text||'')],['导出 TXT',()=>download('pdf-extracted.txt',result.pages.map(p=>`第 ${p.page} 页\n${p.text}`).join('\n\n'))],['导出 JSON',()=>download('pdf-extracted.json',JSON.stringify(result,null,2),'application/json')]]){const b=document.createElement('button');b.textContent=label;b.onclick=action;actions.append(b);}$('result').append(pager,pre,actions); } async function initialize(){ try{ session=await api('/api/session');if(!session.authenticated)throw Error('请先在工作台登录,再打开应用。'); const lease=new URLSearchParams(location.search).get('lease'); state=await api('/api/preview'+(lease?'?preview_id='+encodeURIComponent(lease):''));if(state.status!=='ready')throw Error('本次预览已结束,请从工作台重新打开应用。'); if(lease&&lease!==state.id)throw Error('本次预览已结束,请从对应工程重新打开。'); await watchPreview(state.id,session.csrf,'/api/preview/client'); const info=descriptions[state.scenario];if(!info)throw Error('请从工作台选择对应应用。'); $('title').textContent=info[0];$('appName').textContent=info[0];document.title=info[0];$('description').textContent=info[1];$('inputTitle').textContent=info[2];$('serviceState').textContent='可使用';$('workspace').hidden=false; if(['webapp','business-app'].includes(state.scenario)){ document.querySelector('main').classList.add('generated-app'); document.querySelector('.intro').hidden=true; const frame=document.createElement('iframe');frame.title='本次生成的网页应用';frame.className='generated-frame'; frame.setAttribute('sandbox','allow-scripts allow-modals');frame.referrerPolicy='no-referrer'; frame.addEventListener('load',()=>frame.focus()); if(state.scenario==='business-app')installBusinessBridge(frame); frame.src='/preview-generated/?lease='+encodeURIComponent(state.id); $('workspace').replaceWith(frame); }else if(state.scenario==='erp-orders'){orders();} else{({erp,calculator,pdf}[state.scenario])();notice('请填写信息并提交。');} }catch(e){$('title').textContent='应用暂不可用';$('description').textContent=e.message;$('serviceState').textContent='请重新打开';} } initialize();