v1.1.55: split large files + CRUD scenario editor

Backend (5→7 files):
- api_test.py: 622→479, terraform functions → operations/terraform.py (142)
- api_scenario.py: 241→split into run (153) + defs (108) with _validate_steps()
- db/scenario_defs.py: +client_id, stand, is_seed in list_definitions

Frontend (1→10 files):
- app.js: 554→16 (loader), split into:
  utils.js (45), instances.js (89), operations.js (249),
  history.js (35), scenario-list.js (90)
- New CRUD: scenario-form.js (128), create (25), edit (12), delete (13)

Max file size: JS 249, PY 479
This commit is contained in:
2026-07-30 22:02:22 +04:00
parent 189a2779d6
commit a96658b9b5
18 changed files with 1126 additions and 706 deletions
+35
View File
@@ -0,0 +1,35 @@
// history.js — история тестов
let historyOpen=false;
async function toggleHistory(){
const body=document.getElementById('history-body');
historyOpen=!historyOpen;
body.style.display=historyOpen?'block':'none';
if(historyOpen) await loadHistory();
}
async function loadHistory(){
const body=document.getElementById('history-body');
if(!body||body.style.display==='none') return;
try{
const r=await fetch('/api/history');
const rows=await r.json();
if(!rows||!rows.length){body.innerHTML='<span style="color:var(--muted);font-size:11px;">Нет записей</span>'; return;}
let html='<table style="width:100%;font-size:11px;">';
html+='<tr><th style="padding:2px 6px;">Время</th><th style="padding:2px 6px;">Операция</th><th style="padding:2px 6px;">Инстанс</th><th style="padding:2px 6px;">Статус</th><th style="padding:2px 6px;">Длит.</th></tr>';
rows.forEach(r=>{
const time=r.created_at?r.created_at.replace('T',' ').substring(0,19):'?';
const cls=r.status==='OK'?'badge-success':'';
html+=`<tr>
<td style="padding:2px 6px;">${time}</td>
<td style="padding:2px 6px;">${_esc(r.op_name||'?')}</td>
<td style="padding:2px 6px;">${_esc(r.display_name||r.instance_uid||'?')}</td>
<td style="padding:2px 6px;"><span class="badge ${cls}" style="font-size:9px;">${_esc(r.status||'?')}</span></td>
<td style="padding:2px 6px;">${r.duration_sec!=null?r.duration_sec.toFixed(1)+'s':'-'}</td>
</tr>`;
});
html+='</table>';
body.innerHTML=html;
}catch(e){body.innerHTML='<span style="color:var(--destructive);font-size:11px;">Ошибка загрузки</span>';}
}
+89
View File
@@ -0,0 +1,89 @@
// instances.js — список инстансов, выбор сервиса, toggle операций
let svcInstances=[], selectedInst=null, selectedOp=null;
let currentSvcId=(window.APP&&window.APP.firstServiceId)||1;
let currentSvcName='';
let currentSvcShort='';
let busy=false;
const AUTOTEST_PREFIX='autotest-';
async function selectService(svcId){
if(busy) return;
currentSvcId=svcId;
selectedInst=null; selectedOp=null; stopPoll();
document.getElementById('params-area').style.display='none';
document.querySelectorAll('.stages-box').forEach(e=>e.remove());
document.querySelectorAll('.svc-item').forEach(e=>e.classList.remove('active'));
const svcEl=document.querySelector(`.svc-item[onclick*="${svcId}"]`);
if(svcEl) svcEl.classList.add('active');
try{
const r=await fetch('/api/operations/'+svcId);
const d=await r.json();
svcInstances=d.instances||[];
currentSvcName=d.svc||'';
currentSvcShort=d.svcShort||'';
const btnSpan=document.querySelector('#create-btn-area span');
if(btnSpan) btnSpan.textContent='+ Создать новый инстанс '+(currentSvcName||'сервиса');
renderInstances();
}catch(e){document.getElementById('inst-list').innerHTML='<span style="color:var(--destructive);font-size:11px;">Ошибка загрузки</span>';}
}
function renderInstances(){
let html='';
svcInstances.forEach(i=>{
const status=i.status||i.explainedStatus||'?';
const sc=status==='running'?'badge-success':'';
html+=`<div class="inst-item" onclick="toggleInstance('${i.instanceUid}')" data-iuid="${i.instanceUid}">
<span style="display:inline-block;width:220px;">${_esc(i.displayName)}</span>
<span style="display:inline-block;width:160px;color:var(--muted);font-size:11px;">${_esc(i.svc||'')}</span>
<span class="badge ${sc}" style="font-size:9px;">${_esc(status)}</span>
</div>`;
html+=`<div class="inst-ops" id="ops-${i.instanceUid}"></div>`;
});
document.getElementById('inst-list').innerHTML=html;
}
async function refreshInstances(){
try{
const r=await fetch('/api/operations/'+currentSvcId);
const d=await r.json();
svcInstances=d.instances||[];
renderInstances();
}catch(e){}
}
async function toggleInstance(iuid){
if(busy) return;
selectedInst=iuid; stopPoll();
document.querySelectorAll('[data-iuid]').forEach(e=>e.classList.toggle('active',e.dataset.iuid===iuid));
document.getElementById('params-area').style.display='none';
const opsEl=document.getElementById('ops-'+iuid);
if(opsEl.classList.contains('open')){opsEl.classList.remove('open');return;}
document.querySelectorAll('.inst-ops').forEach(e=>e.classList.remove('open'));
const inst=svcInstances.find(x=>x.instanceUid===iuid);
const svcId=inst?inst.serviceId:currentSvcId;
try{
const r=await fetch('/api/operations/'+svcId);
const d=await r.json();
let ops=(d.operations||[]).filter(o=>o.operation!=='reconcile'&&o.operation!=='create');
if(inst&&(inst.status||inst.explainedStatus)==='not created'){
ops=ops.filter(o=>o.operation==='delete');
}
opsEl.innerHTML=ops.map(o=>
`<button class="btn btn-sm op-btn ${opClass(o.operation)}" onclick="runOp('${o.operation}',${o.svcOperationId})">${o.operation}</button>`
).join('');
opsEl.classList.add('open');
}catch(e){opsEl.innerHTML='<span style="color:var(--destructive);font-size:11px;">Ошибка загрузки</span>';opsEl.classList.add('open');}
}
function opClass(opName){
if(opName==='modify') return 'op-btn-modify';
if(opName==='suspend') return 'op-btn-suspend';
if(opName==='resume') return 'op-btn-resume';
if(opName==='delete') return 'op-btn-delete';
if(opName==='redeploy') return 'op-btn-redeploy';
return '';
}
// Инициализация
selectService(currentSvcId);
+249
View File
@@ -0,0 +1,249 @@
// operations.js — запуск операций: create, modify, delete, poll, stages
let pollTimer=null;
function makeCreateDisplayName(){
const rand = (Math.random() * 46656 | 0).toString(36).padStart(3, '0');
return currentSvcShort ? currentSvcShort+'-'+rand : rand;
}
function findInstName(){
const i=svcInstances.find(x=>x.instanceUid===selectedInst);
return i?i.displayName:selectedInst;
}
function stopPoll(){
if(pollTimer){clearInterval(pollTimer);pollTimer=null;}
}
async function startCreate(){
if(busy) return;
selectedInst=null; stopPoll();
document.querySelectorAll('[data-iuid]').forEach(e=>e.classList.remove('active'));
document.querySelectorAll('.inst-ops').forEach(e=>e.classList.remove('open'));
try{
const r=await fetch('/api/operations/'+currentSvcId);
const d=await r.json();
const createOp=d.operations.find(o=>o.operation==='create');
const opId=createOp?createOp.svcOperationId:18;
showParams(opId,'create');
}catch(e){
showParams(18,'create');
}
}
function runOp(opName,opId){
if(busy) return;
stopPoll();
showParams(opId,opName);
}
function showParams(opId,opName){
selectedOp={opId,opName,svcId:currentSvcId};
document.getElementById('params-area').style.display='block';
document.querySelectorAll('.stages-box').forEach(e=>e.remove());
document.getElementById('test-status').textContent='';
const isCreate=opName==='create';
const qs=isCreate?'' : `?instanceUid=${selectedInst}`;
fetch('/api/params/'+opId+qs).then(r=>r.json()).then(async data=>{
if(data.error){document.getElementById('params-form').innerHTML=`<span style="color:var(--destructive);">Ошибка: ${_esc(data.error)}</span>`;return;}
const params=data.params||data;
if(!Array.isArray(params)){document.getElementById('params-form').innerHTML=`<span style="color:var(--destructive);">Неверный формат параметров</span>`;return;}
let allInst=[];
const needRefs=params.some(p=>p.refSvcId);
if(needRefs){
try{const r=await fetch('/api/instances/list');const list=await r.json();allInst=list||[];}catch(e){}
}
const form=document.getElementById('params-form');
const displayNameValue=isCreate?makeCreateDisplayName():'';
const createHeader=isCreate?`<div style="font-weight:600;font-size:13px;margin-bottom:8px;color:var(--brand-primary);">Создание: ${_esc(currentSvcName)}</div>`:'';
const opHeader=!isCreate?`<div style="font-weight:600;font-size:13px;margin-bottom:8px;color:var(--brand-primary);">${_esc(opName)}${_esc(findInstName())}</div>`:'';
form.innerHTML=createHeader+opHeader+(opName==='create'?`<div class="param-row"><label class="req">displayName</label><span style="font-size:12px;color:var(--muted);white-space:nowrap;">${AUTOTEST_PREFIX}</span><input type="text" id="param-displayname" value="${_esc(displayNameValue)}" autocomplete="off"></div>`:'')
+ params.map(p=>renderParamRow(p,allInst)).join('');
const btn=document.getElementById('btn-test');
btn.style.display='inline-flex';
btn.textContent='Запустить';
btn.onclick=()=>{
let bad=[];
document.querySelectorAll('#params-form [data-type="map"]').forEach(el=>{if(!validateJson(el,true)) bad.push(el);});
if(bad.length>0){
document.getElementById('test-status').innerHTML=`<span class="badge">Ошибка</span> ${bad.length} полей с невалидным JSON — поправьте и нажмите Запустить снова`;
return;
}
const pp=collectParams();
executeOp(pp);
};
}).catch(e=>{
document.getElementById('params-form').innerHTML=`<span style="color:var(--destructive);">Ошибка загрузки: ${_esc(e.message)}</span>`;
});
}
function renderParamRow(p,allInst){
const req=p.isRequired;
const hasDfl=p.defaultValue!==null&&p.defaultValue!==undefined&&p.defaultValue!=='';
const labelCls=req?(hasDfl?'req':'req-nodfl'):'';
const dfl=hasDfl?p.defaultValue:(req?'':'');
const vl=p.valueList;
const isMap=(p.dataType||'').startsWith('map');
let input;
if(vl&&Array.isArray(vl)){
input=`<select name="p_${p.svcOperationCfsParamId}" data-type="${_esc(p.dataType)}">${vl.map(v=>`<option value="${_esc(v)}" ${v==dfl?'selected':''}>${_esc(v)}</option>`).join('')}</select>`;
}else if(p.refSvcId){
const refInsts=allInst.filter(i=>i.serviceId===p.refSvcId&&i.explainedStatus!=='deleted');
let opts=refInsts.map(i=>`<option value="${_esc(i.instanceUid)}" ${i.instanceUid===dfl?'selected':''}>${_esc(i.displayName)}</option>`).join('');
if(!dfl) opts='<option value="">— выбрать —</option>'+opts;
input=`<select name="p_${p.svcOperationCfsParamId}" data-type="ref">${opts}</select>`;
}else if(p.dataType==='boolean'){
input=`<select name="p_${p.svcOperationCfsParamId}" data-type="boolean"><option value="true" ${dfl==='true'||dfl===true?'selected':''}>true</option><option value="false" ${dfl==='false'||dfl===false?'selected':''}>false</option></select>`;
}else if(p.dataDescriptor&&isMap){
return renderMapFixedRow(p,dfl);
}else{
const dt=isMap?'map':'';
input=`<input type="text" name="p_${p.svcOperationCfsParamId}" value="${_esc(dfl)}" data-type="${dt}" placeholder="${req&&!hasDfl?'обязательно':''}"${isMap?' onblur="validateJson(this)"':''}>`;
if(isMap) input+=`<span class="json-err" style="display:none;color:var(--destructive);font-size:10px;margin-left:4px;"></span>`;
}
return `<div class="param-row"><label class="${labelCls}">${_esc(p.name)}</label>${input}</div>`;
}
function renderMapFixedRow(p,dfl){
const dd=p.dataDescriptor;
let subHtml='';
let dflObj={};
try{dflObj=JSON.parse(dfl||'{}');}catch(e){}
Object.keys(dd).forEach(subKey=>{
const sub=dd[subKey];
const subDfl=dflObj[subKey]!==undefined?dflObj[subKey]:(sub.defaultValue||'');
const subVl=sub.valueList;
const subReq=sub.isRequired;
const subNoDfl=subReq&&!subDfl&&subDfl!==0&&subDfl!==false;
const subLblCls=subNoDfl?'req-nodfl':'';
let si;
if(subVl&&Array.isArray(subVl)){
si=`<select name="p_${p.svcOperationCfsParamId}.${subKey}" data-type="mapchild">${subVl.map(v=>`<option value="${_esc(v)}" ${v==subDfl?'selected':''}>${_esc(v)}</option>`).join('')}</select>`;
}else if(sub.dataType==='boolean'){
si=`<select name="p_${p.svcOperationCfsParamId}.${subKey}" data-type="mapchild"><option value="true" ${subDfl==='true'||subDfl===true?'selected':''}>true</option><option value="false" ${subDfl==='false'||subDfl===false?'selected':''}>false</option></select>`;
}else{
si=`<input type="text" name="p_${p.svcOperationCfsParamId}.${subKey}" value="${_esc(subDfl)}" data-type="mapchild">`;
}
subHtml+=`<div class="param-row"><label class="${subLblCls}">${_esc(subKey)}</label>${si}</div>`;
});
return `<div class="param-row"><label class="${labelCls}">${_esc(p.name)}</label></div><div style="border-left:2px solid var(--brand-gray);margin-left:8px;padding:0 0 4px 8px;">${subHtml}</div>`;
}
function collectParams(){
const pp={};
const nested={};
document.querySelectorAll('#params-form [name^="p_"]').forEach(el=>{
let v=el.value;
const dt=el.dataset.type||'';
if(dt==='mapchild'){
const name=el.name.replace('p_','');
const dot=name.indexOf('.');
const parentKey=name.substring(0,dot);
const subKey=name.substring(dot+1);
if(!nested[parentKey]) nested[parentKey]={};
nested[parentKey][subKey]=v;
return;
}
if(dt==='array'||dt.startsWith('array')) v=JSON.stringify([v]);
if(dt==='map'||dt==='map-fixed') v=v||'{}';
pp[el.name.replace('p_','')]=v;
});
for(const pk in nested) pp[pk]=JSON.stringify(nested[pk]);
return pp;
}
function setFinishedState(statusText, statusClass, statusError, statusDuration, instanceName){
busy=false;
document.querySelectorAll('.inst-ops.open').forEach(e=>e.classList.remove('open'));
const btn=document.getElementById('btn-test');
btn.disabled=false;
btn.textContent='Готово';
btn.onclick=null;
const opName=selectedOp?.opName||'операция';
const durationText=statusDuration!==undefined&&statusDuration!==null?`${statusDuration}s`:'0s';
const extra=_esc(statusError||'');
const instName=_esc(instanceName||findInstName()||selectedInst||'');
document.getElementById('test-status').innerHTML=` <span class="badge ${statusClass}">${statusText}</span> <span style="color:var(--muted);">${opName}</span> <span style="color:var(--muted);">${durationText}</span> <span style="color:var(--muted);">${instName}</span> ${extra}`;
}
function setRunningState(opName, displayName){
const btn=document.getElementById('btn-test');
btn.textContent=opName+'...';
document.getElementById('test-status').textContent=' ⏳ '+ (displayName||opName) +' выполняется...';
}
async function executeOp(params){
busy=true;
stopPoll();
const isCreate=selectedOp?.opName==='create';
const displayNameInput=document.getElementById('param-displayname');
const displayNameSuffix=(displayNameInput?.value||'').trim();
const displayName=isCreate ? `${AUTOTEST_PREFIX}${displayNameSuffix || makeCreateDisplayName()}` : findInstName();
document.getElementById('params-area').style.display='block';
document.getElementById('params-form').innerHTML='';
const btn=document.getElementById('btn-test');
btn.style.display='inline-flex';
btn.textContent=selectedOp.opName+'...';
btn.disabled=true;
setRunningState(selectedOp.opName, displayName);
const instId=selectedInst||'';
const afterEl=instId?document.getElementById('ops-'+instId):null;
document.querySelectorAll('.stages-box').forEach(e=>e.remove());
const stagesBox=document.createElement('div');
stagesBox.className='stages-box';
stagesBox.style.cssText='max-height:200px;overflow-y:auto;padding:4px 8px;margin-left:16px;background:var(--brand-grey-light);border-radius:4px;';
if(afterEl){afterEl.after(stagesBox);}
else{document.getElementById('create-btn-area').after(stagesBox);}
try{
const r=await fetch('/api/test',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({
serviceId:currentSvcId, operation:selectedOp.opName, svcOperationId:selectedOp.opId,
params, instanceUid:selectedInst||'', displayName:isCreate?displayName:''
})});
const d=await r.json();
if(d.status==='FAIL'){busy=false;document.getElementById('test-status').innerHTML=` <span class="badge">FAIL</span> ${_esc(d.error||'')}`;btn.disabled=false;return;}
if(d.status==='OK'&&(d.opUid||'').startsWith('cmdb-')){
busy=false;
setFinishedState('OK','badge-success','',0,d.displayName);
try{await refreshInstances();}catch(e){}
if(historyOpen) try{await loadHistory();}catch(e){}
return;
}
const opUid=d.opUid;
const instanceName=d.displayName||displayName;
let _pollErrors=0;
pollTimer=setInterval(async()=>{
try{
const sr=await fetch('/api/test/status/'+opUid);
const sd=await sr.json();
_pollErrors=0;
showStages(sd.stages||[]);
if(sd.status!=='RUNNING'){
stopPoll();
setFinishedState(sd.status, sd.status==='OK'?'badge-success':'badge', sd.error||sd.errorLog, sd.duration, sd.displayName||instanceName);
await refreshInstances();
if(historyOpen) await loadHistory();
}
}catch(e){
_pollErrors++;
if(_pollErrors>=5){stopPoll();setFinishedState('TIMEOUT','','Связь потеряна',0,instanceName);}
}
},2000);
}catch(e){
busy=false;
document.getElementById('test-status').textContent=' Ошибка: '+e.message;
btn.disabled=false;
}
}
function showStages(stages){
if(!stages||!stages.length) return;
let html='<div style="font-size:11px;font-weight:600;color:var(--muted);margin-top:4px;">Этапы</div>';
stages.forEach(s=>{
const done=!!s.dtFinish;
const icon=done?(s.isSuccessful?'✅':'❌'):'⏳';
html+=`<div style="font-size:11px;padding:2px 0;">${icon} ${_esc(s.stage)}${(s.duration||0).toFixed(1)}s</div>`;
});
const boxes=document.querySelectorAll('.stages-box');
if(boxes.length) boxes[boxes.length-1].innerHTML=html;
}
+25
View File
@@ -0,0 +1,25 @@
// scenario-create.js — создание и клонирование сценария
async function createScenario() {
showScenarioEditor(null);
}
async function cloneScenario(defId, origName) {
const newName = prompt('Имя нового сценария (копия «' + origName + '»):', origName + '_copy');
if (!newName) return;
try {
const r = await fetch('/api/scenario/definitions/' + defId);
const def = await r.json();
if (def.error) { alert(def.error); return; }
const rr = await fetch('/api/scenario/definitions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newName, steps: def.steps })
});
const d = await rr.json();
if (d.error) { alert(d.error); return; }
await loadScenarios();
} catch (e) {
alert('Ошибка клонирования: ' + e.message);
}
}
+13
View File
@@ -0,0 +1,13 @@
// scenario-delete.js — удаление сценария
async function deleteScenario(defId, name) {
if (!confirm('Удалить сценарий «' + name + '»?')) return;
try {
const r = await fetch('/api/scenario/definitions/' + defId, { method: 'DELETE' });
const d = await r.json();
if (d.error) { alert(d.error); return; }
await loadScenarios();
} catch (e) {
alert('Ошибка: ' + e.message);
}
}
+12
View File
@@ -0,0 +1,12 @@
// scenario-edit.js — редактирование существующего сценария
async function editScenario(defId) {
try {
const r = await fetch('/api/scenario/definitions/' + defId);
const def = await r.json();
if (def.error) { alert(def.error); return; }
showScenarioEditor(def);
} catch (e) {
alert('Ошибка загрузки: ' + e.message);
}
}
+128
View File
@@ -0,0 +1,128 @@
// scenario-form.js — общий редактор шагов сценария (create + edit)
let scenarioEditorState = null; // {defId, version, name, steps:[]}
// steps: [{service_id, operation, params: [["key","val"],...]}]
function showScenarioEditor(def) {
const body = document.getElementById('scenario-body');
scenarioEditorState = def ? {
defId: def.id, version: def.version, name: def.name,
steps: (def.steps || []).map(s => ({
service_id: s.service_id, operation: s.operation,
params: Object.entries(s.params || {})
}))
} : { defId: null, version: 1, name: '', steps: [] };
renderEditor();
}
function renderEditor() {
const st = scenarioEditorState;
let html = '<div style="font-size:12px;">';
html += '<div style="margin-bottom:6px;"><label style="font-size:11px;">Название:</label><br>';
html += `<input type="text" id="scenario-name" value="${_esc(st.name)}" style="width:100%;padding:4px;" placeholder="my_test">`;
html += '</div>';
html += '<div style="margin-bottom:6px;font-size:11px;font-weight:600;">Шаги:</div>';
st.steps.forEach((s, idx) => {
html += renderStepRow(idx, s);
});
html += `<button class="btn btn-sm" style="font-size:11px;margin-top:4px;" onclick="addStep()">+ Добавить шаг</button>`;
html += '<div style="margin-top:8px;">';
html += `<button class="btn btn-sm" style="font-size:11px;background:var(--brand-primary);color:#fff;" onclick="saveScenario()">Сохранить</button> `;
html += '<button class="btn btn-sm" style="font-size:11px;" onclick="loadScenarios()">Отмена</button>';
html += '</div></div>';
body.innerHTML = html;
}
function renderStepRow(idx, step) {
const svcId = step.service_id || '';
const op = step.operation || '';
const params = step.params || [];
let html = `<div style="border:1px solid var(--brand-gray);border-radius:4px;padding:6px;margin:4px 0;" id="step-${idx}">`;
html += `<div style="font-size:10px;color:var(--muted);margin-bottom:4px;">Шаг ${idx+1}`;
html += ` <button class="btn btn-sm" style="font-size:9px;padding:0 4px;" onclick="removeStep(${idx})">✕</button>`;
html += `</div>`;
// Сервис — текстовое поле с подсказкой (ID или имя)
html += `<input type="number" id="step-${idx}-svc" value="${svcId}" placeholder="service_id" style="width:80px;padding:2px;font-size:11px;" onchange="onStepChange(${idx})"> `;
// Операция
html += `<input type="text" id="step-${idx}-op" value="${_esc(op)}" placeholder="create" style="width:100px;padding:2px;font-size:11px;"> `;
html += '<div style="margin-top:2px;">';
params.forEach(([k, v], pi) => {
html += `<div style="display:flex;gap:4px;align-items:center;margin:2px 0;">`;
html += `<input type="text" id="step-${idx}-pk-${pi}" value="${_esc(k)}" placeholder="param" style="width:100px;padding:2px;font-size:10px;">`;
html += `<span>=</span>`;
html += `<input type="text" id="step-${idx}-pv-${pi}" value="${_esc(v)}" placeholder="value" style="width:120px;padding:2px;font-size:10px;">`;
html += `<button class="btn btn-sm" style="font-size:9px;padding:0 3px;" onclick="removeParam(${idx},${pi});renderEditor();">✕</button>`;
html += `</div>`;
});
html += `<button class="btn btn-sm" style="font-size:9px;margin-top:2px;" onclick="addParam(${idx});renderEditor();">+ Параметр</button>`;
html += '</div></div>';
return html;
}
function addStep() {
scenarioEditorState.steps.push({ service_id: 1, operation: 'create', params: [] });
renderEditor();
}
function removeStep(idx) {
scenarioEditorState.steps.splice(idx, 1);
renderEditor();
}
function addParam(idx) {
scenarioEditorState.steps[idx].params.push(['', '']);
}
function removeParam(idx, pi) {
scenarioEditorState.steps[idx].params.splice(pi, 1);
}
function onStepChange(idx) { /* placeholder for future auto-load */ }
function collectFormSteps() {
const st = scenarioEditorState;
const name = (document.getElementById('scenario-name')?.value || '').trim();
const steps = [];
st.steps.forEach((_, idx) => {
const svcEl = document.getElementById(`step-${idx}-svc`);
const opEl = document.getElementById(`step-${idx}-op`);
const svcId = parseInt(svcEl?.value) || 0;
const operation = (opEl?.value || '').trim();
const params = {};
st.steps[idx].params.forEach((__, pi) => {
const k = document.getElementById(`step-${idx}-pk-${pi}`)?.value?.trim();
const v = document.getElementById(`step-${idx}-pv-${pi}`)?.value || '';
if (k) params[k] = v;
});
steps.push({ service_id: svcId, operation, params });
});
return { name, steps };
}
async function saveScenario() {
const { name, steps } = collectFormSteps();
if (!name) { alert('Введите название'); return; }
if (!steps.length) { alert('Добавьте хотя бы один шаг'); return; }
for (let i = 0; i < steps.length; i++) {
if (!steps[i].service_id) { alert('Шаг ' + (i+1) + ': укажите service_id'); return; }
if (!steps[i].operation) { alert('Шаг ' + (i+1) + ': укажите operation'); return; }
}
const st = scenarioEditorState;
const isNew = !st.defId;
const url = isNew ? '/api/scenario/definitions' : '/api/scenario/definitions/' + st.defId;
const method = isNew ? 'POST' : 'PUT';
const body = isNew ? { name, steps } : { name, steps, version: st.version };
try {
const r = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
const d = await r.json();
if (r.status === 409) {
alert('⚠️ Конфликт версий — кто-то уже изменил сценарий. Обновите страницу.');
return;
}
if (d.error) { alert(d.error); return; }
if (isNew && d.id) st.defId = d.id;
if (d.version) st.version = d.version;
await loadScenarios();
} catch (e) {
alert('Ошибка сохранения: ' + e.message);
}
}
+90
View File
@@ -0,0 +1,90 @@
// scenario-list.js — список сценариев, запуск, поллинг
let scenarioOpen=false, scenarioPollTimer=null;
async function toggleScenario(){
const body=document.getElementById('scenario-body');
scenarioOpen=!scenarioOpen;
body.style.display=scenarioOpen?'block':'none';
if(!scenarioOpen){ stopScenarioPoll(); return; }
await loadScenarios();
}
async function loadScenarios(){
const body=document.getElementById('scenario-body');
try{
const [sr, srHistory]=await Promise.all([
fetch('/api/scenarios').then(r=>r.json()),
fetch('/api/scenario/status').then(r=>r.json()),
]);
let html='';
html+=`<button class="btn btn-sm" style="font-size:10px;margin-bottom:4px;" onclick="createScenario()">+ Создать сценарий</button>`;
if(sr.length){
html+='<div style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:4px;">';
sr.forEach(s=>{
const seed = s.is_seed;
html+=`<div style="display:inline-flex;gap:2px;align-items:center;">`;
html+=`<button class="btn btn-sm" style="font-size:11px;" onclick="runScenario(${s.id})" title="Запустить">▶ ${_esc(s.name)} <span style="color:var(--muted);">(${s.steps} шагов)</span></button>`;
if(!seed) html+=`<button class="btn btn-sm" style="font-size:9px;padding:0 4px;" onclick="editScenario(${s.id})" title="Редактировать">✏</button>`;
html+=`<button class="btn btn-sm" style="font-size:9px;padding:0 4px;" onclick="cloneScenario(${s.id},'${_esc(s.name)}')" title="Клонировать">⎘</button>`;
if(!seed) html+=`<button class="btn btn-sm" style="font-size:9px;padding:0 4px;color:var(--destructive);" onclick="deleteScenario(${s.id},'${_esc(s.name)}')" title="Удалить">🗑</button>`;
if(seed) html+=`<span style="font-size:8px;color:var(--muted);">seed</span>`;
html+=`</div>`;
});
html+='</div>';
}else{
html+='<span style="color:var(--muted);font-size:11px;">Нет сценариев в БД</span>';
}
const curVer=window.APP&&window.APP.version||'';
const verHistory=srHistory&&srHistory.filter(r=>r.app_version===curVer);
if(verHistory && verHistory.length){
const last=verHistory[0];
const icon=last.status==='OK'?'✅':last.status==='FAIL'?'❌':last.status==='RUNNING'?'⏳':'⏱';
const time=last.created_at?last.created_at.replace('T',' ').substring(0,19):'?';
html+=`<div style="font-size:11px;margin-top:4px;color:var(--muted);">Последний: ${icon} ${_esc(last.scenario_name)}${last.status} (шаг ${last.current_step}/${last.total_steps}) ${last.duration_sec!=null?last.duration_sec.toFixed(1)+'s':''}${time}</div>`;
if(last.error_log) html+=`<div style="font-size:10px;color:var(--destructive);">${_esc(last.error_log)}</div>`;
}
body.innerHTML=html;
}catch(e){body.innerHTML='<span style="color:var(--destructive);font-size:11px;">Ошибка загрузки</span>';}
}
async function runScenario(defId){
if(busy){ return; }
busy=true;
stopScenarioPoll();
const body=document.getElementById('scenario-body');
body.innerHTML=`<div style="font-size:11px;">⏳ Запуск...</div>`;
try{
const r=await fetch('/api/scenario/run',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({definition_id:defId})});
const d=await r.json();
if(d.error){ body.innerHTML=`<span style="color:var(--destructive);">Ошибка: ${_esc(d.error)}</span>`; busy=false; return; }
const runId=d.run_id;
if(!runId){ body.innerHTML=`<span style="color:var(--destructive);">Ошибка: нет run_id в ответе</span>`; busy=false; return; }
scenarioPollTimer=setInterval(async()=>{
try{
const sr=await fetch('/api/scenario/run/'+runId);
if(!sr.ok){ return; }
const last=await sr.json();
if(!last||last.error) return;
const icon=last.status==='OK'?'✅':last.status==='FAIL'?'❌':last.status==='RUNNING'?'⏳':'⏱';
const time=last.created_at?last.created_at.replace('T',' ').substring(0,19):'?';
let html=`<div style="font-size:11px;">${icon} ${_esc(last.scenario_name)}${last.status} (шаг ${last.current_step}/${last.total_steps}) ${last.duration_sec!=null?last.duration_sec.toFixed(1)+'s':''}${time}</div>`;
if(last.error_log) html+=`<div style="font-size:10px;color:var(--destructive);">${_esc(last.error_log)}</div>`;
body.innerHTML=html;
if(last.status!=='RUNNING'){
stopScenarioPoll();
busy=false;
await refreshInstances();
if(historyOpen) await loadHistory();
}
}catch(e){}
},3000);
}catch(e){
body.innerHTML=`<span style="color:var(--destructive);">Ошибка: ${_esc(e.message)}</span>`;
busy=false;
}
}
function stopScenarioPoll(){
if(scenarioPollTimer){ clearInterval(scenarioPollTimer); scenarioPollTimer=null; }
}
+45
View File
@@ -0,0 +1,45 @@
// utils.js — общие хелперы: _esc, busy lock, validateJson, лог-панель
function _esc(s){
/* HTML-экранирование: " → &quot; & → &amp; < → &lt; */
return String(s||'').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;');
}
function validateJson(el,quiet){
/* Проверить что значение в поле — валидный JSON.
quiet=true — не менять внешний вид (для batch-проверки перед отправкой). */
const errEl=el.parentElement.querySelector('.json-err');
const v=el.value.trim();
if(!v) return true;
try{ JSON.parse(v); }
catch(e){
if(!quiet&&errEl){ errEl.style.display='inline'; errEl.textContent='Ошибка JSON: '+e.message; }
el.style.borderColor='var(--destructive)';
return false;
}
if(!quiet&&errEl) errEl.style.display='none';
el.style.borderColor='';
return true;
}
// === Панель логов ===
let logPollTimer=null;
function startLogPoll(){
if(logPollTimer) return;
logPollTimer=setInterval(async()=>{
const el=document.getElementById('log-panel');
if(!el||el.style.display==='none') return;
try{
const r=await fetch('/api/log');
const lines=await r.json();
el.innerHTML=lines.map(l=>`<div>${_esc(l)}</div>`).join('');
el.scrollTop=el.scrollHeight;
}catch(e){}
},2000);
}
function toggleLog(){
const el=document.getElementById('log-panel');
if(!el) return;
if(el.style.display==='none'){ el.style.display='block'; startLogPoll(); }
else el.style.display='none';
}