Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

14.5 KB
Raw Blame
<script>
import Icon from './Icon.svelte';
import {onMount} from 'svelte';
import {page} from '$app/stores';
import {api} from './api.js';
import {setQuery} from './navigation.mjs';
import ResponseBrowser from './ResponseBrowser.svelte';
import {executionPhases} from './chart-timeline.mjs';
export let run;export let revision=0;export let running=false;
/** @type {any} */ export let result=null;
let data=null,listing=null,error='',busy=false,request=0,mounted=false,measured=false,root,width=900,observer,timer,hover=null,hoverCursor=0,brush=null,drawer,selected=null,detailBusy=false;
let filter=$page.url.searchParams.get('outcome')||'all',from=Number($page.url.searchParams.get('from')||0),to=$page.url.searchParams.has('to')?Number($page.url.searchParams.get('to')):null,stack=[{}],search='',knownRevision=revision;
const labels={match:'Status matched',missing:'ID not found',mismatch:'Status mismatch',pending:'Not compared',creation_unknown:'Creation unverified',confirmation_failed:'Confirmation failed'};
$: plotWidth=Math.max(260,width);
$: plotRight=plotWidth-12;
$: plotSpan=plotRight-40;
$: visibleKeys=['all','confirmation_failed'].includes(filter)?['match','missing','mismatch','pending','creation_unknown']:filter==='discrepancies'?['missing','mismatch','creation_unknown']:[filter];
$: maximum=Math.max(1,...(data?.mode==='buckets'?data.rows.map(row=>visibleKeys.reduce((sum,k)=>sum+(row[k]||0),0)):[1]));
$: phases=executionPhases(run.timeline||[],run.telemetry||[],run.activity||[],run.startedAt,data?.duration/1000||0);
$: visiblePhases=phases.map(phase=>({...phase,from:Math.max(data?.from||0,phase.start*1000),to:Math.min(data?.to||0,phase.end*1000)})).filter(phase=>phase.to>phase.from);
const phaseAt=ms=>phases.find(phase=>ms>=phase.start*1000&&ms<phase.end*1000)?.label||'';
const countLabel=(label,count)=>count==null?label:`${label} · ${count.toLocaleString()}`;
$: exportUrl=`/api/runs/${encodeURIComponent(run.id)}/export?${new URLSearchParams({kind:'payments',filter,from:String(from),...(to==null?{}:{to:String(to)}),search})}`;
$: if(mounted&&revision!==knownRevision){knownRevision=revision;if(!running)load(false);}
const time=ms=>`${(ms/1000).toFixed(ms%1000?1:0)}s`;
const x=ms=>40+(ms-data.from)/(data.to-data.from)*plotSpan;
function sync(){setQuery({outcome:filter==='all'?null:filter,from:from||null,to});}
async function load(reset=true){if(!mounted||!measured)return;const token=++request;busy=true;error='';if(reset)stack=[{}];try{const options={view:'timeline',from,...(to==null?{}:{to}),filter,bars:Math.max(50,Math.min(600,Math.floor(width/5)))};const next=await api.paymentBars(run.id,options);if(token!==request)return;data=next;hover=null;if(!next.legacy&&!next.preparing)listing=await api.paymentPage(run.id,{from,...(to==null?{}:{to}),filter,search,...stack.at(-1)});}catch(e){if(token===request)error=running?'Preparing payment view…':e.message;}finally{if(token===request)busy=false;}}
function change(){hover=null;sync();load();}
function zoom(a,b){from=Math.max(0,Math.floor(a));to=Math.max(from+1,Math.min(data.duration,Math.ceil(b)));change();}
function reset(){from=0;to=null;change();}
async function nextError(){try{const row=await api.nextDiscrepancy(run.id,to==null?from:to);if(!row){error='No later discrepancies. Reset the view to start again.';return;}filter='discrepancies';zoom(Math.max(0,row.elapsed_ms-100),row.elapsed_ms+101);}catch(e){error=e.message;}}
function pointer(event){const rect=event.currentTarget.getBoundingClientRect();return Math.max(data.from,Math.min(data.to,data.from+((event.clientX-rect.left)/rect.width*plotWidth-40)/plotSpan*(data.to-data.from)));}
function inspect(event){if(!data||data.legacy||data.preparing)return;const at=pointer(event);hoverCursor=at;hover=data.mode==='buckets'?data.rows.find(row=>at>=row.from&&at<row.to):data.rows[Math.max(0,Math.min(data.rows.length-1,Math.floor((at-data.from)/(data.to-data.from)*data.rows.length)))];}
const equalsPrimary=event=>event.button===0;
function brushEnd(event){if(data?.mode==='payments'){if(equalsPrimary(event)&&hover)openPayment(hover);return;}if(brush==null)return;const end=pointer(event),begin=brush;brush=null;if(Math.abs(end-begin)>(data.to-data.from)*.015)zoom(Math.min(begin,end),Math.max(begin,end));else if(hover){if(data.mode==='payments')openPayment(hover);else zoom(hover.from,hover.to);}}
async function openPayment(row){selected=row;drawer.showModal();detailBusy=true;try{selected=await api.paymentDetail(run.id,{rowId:row.id,payment:row.payment_id,merchant:row.merchant_id});}catch(e){error=e.message;}finally{detailBusy=false;}}
async function pageList(next){stack=next?[...stack,listing.next]:stack.slice(0,-1);load(false);}
onMount(()=>{mounted=true;observer=new ResizeObserver(entries=>{width=entries[0].contentRect.width;if(!measured){measured=true;load();}});observer.observe(root);timer=setInterval(()=>{if(measured&&running&&!busy)load(false);},2000);return()=>{mounted=false;request++;observer.disconnect();clearInterval(timer);};});
</script>
<section bind:this={root} class="payment-chart" aria-label="Payment reconciliation">
<div class="toolbar"><label>Show<select bind:value={filter} onchange={change}><option value="all">All outcomes</option><option value="match">{countLabel('Status matched',data?.totals?.match)}</option><option value="discrepancies">Needs attention</option><option value="creation_unknown">{countLabel('Creation unverified',data?.totals?.creation_unknown)}</option><option value="confirmation_failed">{countLabel('Confirmation failed',result?.confirmationFailed)}</option><option value="missing">{countLabel('ID not found',data?.totals?.missing)}</option><option value="mismatch">{countLabel('Status mismatch',data?.totals?.mismatch)}</option><option value="pending">{countLabel('Not compared',data?.totals?.pending)}</option></select></label><div class="actions">{#if data?.totals?.missing||data?.totals?.mismatch||data?.totals?.creation_unknown}<button class="quiet" disabled={busy} onclick={nextError}>Next issue</button>{/if}{#if from||to!=null}<button class="quiet" onclick={reset}>Full timeline</button>{/if}</div></div>
{#if error}<p class="invalid" role="alert">{error}<button class="quiet" onclick={()=>load()}>Retry</button></p>{/if}
{#if data?.legacy}<p>Payment bars are unavailable for this earlier run.</p>
{:else if data?.preparing}<p role="status">Preparing payment view…</p>
{:else if data}
<div class="plot" aria-busy={busy}>
<svg viewBox={`0 0 ${plotWidth} 260`} role="img" aria-label="Recorded outcomes over elapsed time, with hold, ramp and verified outage periods. Green: status matched; red: status discrepancies; amber: creation unverified; grey: not compared. Drag to zoom." onpointermove={inspect} onpointerleave={()=>{if(brush==null)hover=null;}} onpointerdown={e=>{inspect(e);if(e.button===0&&data.mode==='buckets'){brush=pointer(e);e.currentTarget.setPointerCapture(e.pointerId);}}} onpointerup={brushEnd} onpointercancel={()=>brush=null}>
{#each visiblePhases as phase}<g><title>{phase.label} · {time(phase.start*1000)}–{time(phase.end*1000)}{phase.kind==='outage'?' · verified interruption through recovery':''}</title><rect x={x(phase.from)} y="35" width={x(phase.to)-x(phase.from)} height="185" fill={phase.kind==='outage'?'#c43b3608':phase.kind==='ramp'?'#0561e205':'transparent'}/><rect x={x(phase.from)} y="13" width={Math.max(0,x(phase.to)-x(phase.from)-1)} height="15" rx="2" fill={phase.kind==='outage'?'#fbe5e3':phase.kind==='ramp'?'#e7effb':'#f0f2f5'}/>{#if x(phase.to)-x(phase.from)>phase.label.length*4.5+2}<text class="phase-label" x={(x(phase.from)+x(phase.to))/2} y="24" text-anchor="middle">{phase.label}</text>{/if}</g>{/each}
{#each (data.mode==='payments'?[0,1]:[0,.5,1]) as fraction}<line x1="40" x2={plotRight} y1={220-fraction*185} y2={220-fraction*185} stroke="#e7ebf2"/><text x="33" y={224-fraction*185} text-anchor="end">{Math.round(maximum*fraction).toLocaleString()}</text>{/each}
{#each data.rows as row,index}
{#if data.mode==='payments'}<rect x={40+(index+.5)/data.rows.length*plotSpan-Math.min(12,Math.max(.5,plotSpan/data.rows.length-1))/2} y="35" width={Math.min(12,Math.max(.5,plotSpan/data.rows.length-1))} height="185" fill={row.outcome==='match'?'#398453':row.outcome==='pending'?'#a5adba':'#c43b36'}/>
{:else}{@const green=visibleKeys.includes('match')?row.match:0}{@const red=(visibleKeys.includes('missing')?row.missing:0)+(visibleKeys.includes('mismatch')?row.mismatch:0)}{@const amber=visibleKeys.includes('creation_unknown')?row.creation_unknown||0:0}{@const grey=visibleKeys.includes('pending')?row.pending:0}{@const barWidth=Math.max(.5,x(row.to)-x(row.from)-1)}
<rect x={x(row.from)} y={220-green/maximum*185} width={barWidth} height={green/maximum*185} fill="#398453"/>
<rect x={x(row.from)} y={220-(green+red)/maximum*185} width={barWidth} height={red/maximum*185} fill="#c43b36"/>
<rect x={x(row.from)} y={220-(green+red+amber)/maximum*185} width={barWidth} height={amber/maximum*185} fill="#d68a25"/>
<rect x={x(row.from)} y={220-(green+red+amber+grey)/maximum*185} width={barWidth} height={grey/maximum*185} fill="#a5adba"/>
{/if}{/each}
{#if brush!=null&&hover}<rect x={x(Math.min(brush,hover.from??hover.elapsed_ms))} y="28" width={Math.abs(x(hover.to??hover.elapsed_ms)-x(brush))} height="192" fill="#0561e222"/>{/if}
{#if hover}<line x1={x(hoverCursor)} x2={x(hoverCursor)} y1="28" y2="220" stroke="#8793a5" stroke-width=".7" stroke-dasharray="3 3"/><text class="hover-seconds" x={Math.max(70,Math.min(plotRight-30,x(hoverCursor)))} y="245" text-anchor="middle">{time(data.mode==='payments'?hover.elapsed_ms:hoverCursor)}</text>{:else}
<text x="40" y="245">{data.mode==='payments'?'Payment 1':time(data.from)}</text><text x={plotRight} y="245" text-anchor="end">{data.mode==='payments'?`Payment ${data.rows.length.toLocaleString()}`:time(data.to)}</text>{/if}
{#if !data.rows.length}<text x={plotWidth/2} y="125" text-anchor="middle">No payments in this view</text>{/if}
</svg>
<div class="tooltip" role="status">{#if hover}{#if data.mode==='payments'}<strong>{time(hover.elapsed_ms)}</strong><span>{labels[hover.outcome]}</span><span>{hover.payment_id}</span>{:else}<strong>{time(hover.from)}–{time(hover.to)}</strong><span>{phaseAt(hover.from)} · {hover.match.toLocaleString()} matched · {(hover.missing+hover.mismatch).toLocaleString()} status differences{hover.creation_unknown?` · ${hover.creation_unknown} creation unverified`:''}{hover.pending?` · ${hover.pending} pending`:''}</span>{/if}{:else}<span>Hover to inspect · drag to zoom</span>{/if}</div>
</div>
<details class="payment-list"><summary>Inspect payments and failed attempts</summary><div class="list-head"><form onsubmit={e=>{e.preventDefault();load();}}><input aria-label="Search payments" placeholder="Payment or merchant ID" bind:value={search}/><button class="secondary" disabled={busy}>Search</button></form><a class="quiet" href={exportUrl} download>Export CSV</a></div>
{#if listing}<div class="table-wrap"><table><thead><tr><th>Time / payment or attempt</th><th>Client / database status</th><th>Outcome</th></tr></thead><tbody>{#each listing.rows as row}<tr><td><button class="quiet payment-link" onclick={()=>openPayment(row)}>{row.payment_id||`Create attempt #${row.event_id}`}</button><small>{time(row.elapsed_ms)} · {row.merchant_id}</small></td><td>{row.recorded_status||'—'} / {row.database_status||'—'}{#if row.failure_category}<small>{row.api_status_code||'Timeout / transport error'} · {row.message||row.operation}</small>{/if}</td><td>{labels[row.outcome]}{#if row.failure_category==='confirmation_failed'}<small>Confirmation failed</small>{/if}</td></tr>{:else}<tr><td colspan="3">No outcomes match.</td></tr>{/each}</tbody></table></div><div class="actions"><button class="secondary" disabled={busy||stack.length===1} onclick={()=>pageList(false)}>Previous</button><small>Page {stack.length}</small><button class="secondary" disabled={busy||!listing.next} onclick={()=>pageList(true)}>Next</button></div>{/if}</details>
{:else}<p role="status">{busy?'Loading payment outcomes…':'Compare recorded payments to display outcomes.'}</p>{/if}
</section>
<dialog class="payment-drawer" bind:this={drawer} aria-label="Payment details"><div class="section-head"><h2>{selected?.payment_id?'Payment details':'Failed create attempt'}</h2><button class="icon-button" aria-label="Close payment details" onclick={()=>drawer.close()}><Icon name="close"/></button></div>{#if selected}<p>{selected.payment_id||`Attempt #${selected.event_id}`}<br/><small>{selected.merchant_id} · {time(selected.elapsed_ms)}</small></p><div class="detail-status"><span>Recorded <strong>{selected.recorded_status||'—'}</strong></span><span>Database <strong>{selected.database_status||'—'}</strong></span><span>{labels[selected.outcome]}{#if selected.failure_category==='confirmation_failed'}<strong>Confirmation failed · {selected.api_status_code||'transport error'}</strong>{/if}</span></div>{#if !selected.payment_id}<p>No payment ID was returned. This response cannot establish whether the application created a payment.</p>{/if}{#if detailBusy}<p>Loading…</p>{:else}{#key selected.id}<ResponseBrowser runId={run.id} payment={selected.payment_id} merchant={selected.merchant_id} event={selected.payment_id?'':String(selected.event_id)}/>{/key}{/if}{/if}</dialog>
<style>.toolbar,.toolbar label,.list-head,.list-head form{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.toolbar{justify-content:space-between}.toolbar label{font-size:12px}.toolbar select{width:220px;min-height:34px;margin:0}.toolbar .actions{margin:0}.plot{margin-top:10px}svg{display:block;width:100%;height:260px;touch-action:none;user-select:none}text{font-size:11px;fill:#8793a5}.tooltip{min-height:32px;font-size:12px;display:flex;gap:12px;align-items:center;flex-wrap:wrap;color:#344054;background:#f7f9fc;padding:8px 12px;border-radius:8px;overflow-wrap:anywhere}small{font-size:11px;color:#667085}.hover-seconds{fill:var(--ink);font-weight:500}.phase-label{fill:#667085;font-size:9px}.payment-list{margin-top:20px;padding-top:18px;border-top:1px solid var(--border)}.payment-list summary{cursor:pointer;font-size:13px;font-weight:600}.list-head{margin:12px 0;justify-content:space-between}.list-head input{width:220px;margin:0}.list-head a{font-size:12px}.payment-link{white-space:normal;padding-left:0;font-size:12px;overflow-wrap:anywhere;text-align:left}td{font-size:12px}td small{display:block}.payment-drawer{margin:0 0 0 auto;height:100dvh;max-height:100dvh;width:min(800px,95vw);max-width:none;border-radius:14px 0 0 14px;padding:24px;overflow:auto}.detail-status{display:flex;gap:24px;flex-wrap:wrap;font-size:12px;margin:20px 0}.detail-status strong{display:block}@media(max-width:600px){.toolbar{gap:0}.toolbar .actions{flex-wrap:wrap}.payment-drawer{padding:16px}}</style>