Files
Investidor-V2/outputs/investmoz-audit-current-20261012/reconcile-csv.mjs
T
nala 287e991486
tests / ci (push) Waiting to run
oportunidades 7
2026-10-13 11:40:29 +02:00

63 lines
5.3 KiB
JavaScript

import fs from 'node:fs/promises';
import path from 'node:path';
import assert from 'node:assert/strict';
import {createRequire} from 'node:module';
import {pathToFileURL,fileURLToPath} from 'node:url';
import {createHash} from 'node:crypto';
const out=path.dirname(fileURLToPath(import.meta.url)),root=path.dirname(path.dirname(out));
const req=createRequire(path.join(root,'storage/app/private/investmoz-v2/portal-audit/legacy-sector-reconciliation-20261010/package.json'));
const {Workbook}=await import(pathToFileURL(req.resolve('@oai/artifact-tool')).href);
const plan=JSON.parse(await fs.readFile(path.join(out,'authoring-plan.json'),'utf8'));
const hash=v=>createHash('sha256').update(v).digest('hex');
const same=(v,s)=>v instanceof Date?new Date(v).getTime()===Date.parse(s):(v==null?'':String(v))===s;
const quote=v=>/[",\r\n]/.test(v)?'"'+v.replaceAll('"','""')+'"':v;
for(const f of plan.files)assert.equal(hash(await fs.readFile(f.path)),f.before_sha256,'Source changed; stop before mutation');
if(process.argv.includes('--inspect')){
const f=plan.files[0],wb=await Workbook.fromCSV((await fs.readFile(f.path,'utf8')).replace(/^\ufeff/,''),{sheetName:'Matriz'});
const sheet=wb.worksheets.getItem('Matriz');
const inspect=await wb.inspect({kind:'region',sheetId:'Matriz',range:'A1:D5',maxChars:2000,tableMaxRows:5,tableMaxCols:4,tableMaxCellChars:90});
await fs.writeFile(path.join(out,'artifact-inspection.json'),JSON.stringify(inspect,null,2));
const preview=Workbook.create(),s=preview.worksheets.add('Excerto');
const cols=[0,headersIndex(f,'Estado'),headersIndex(f,'Evidência funcional')];
const changed=f.before.map((r,i)=>({r,i})).filter(({r,i})=>i>0&&JSON.stringify(r)!==JSON.stringify(f.after[i]));
const shown=[f.before[0],...changed.slice(0,3).map(({r})=>r),changed.find(({r})=>r[0]==='AUD-PROFILE-26')?.r||changed[3]?.r];
s.getRange('A1:C5').values=shown.map(r=>cols.map(c=>r[c].slice(-180)));
s.getRange('A1:C5').format.wrapText=true;s.getRange('A1:C5').format.rowHeightPx=90;
s.getRange('A1:A5').format.columnWidthPx=140;s.getRange('B1:B5').format.columnWidthPx=170;s.getRange('C1:C5').format.columnWidthPx=650;
const img=await preview.render({sheetName:'Excerto',autoCrop:'all',scale:1,format:'png'});
await fs.writeFile(path.join(out,'matrix-before-preview.png'),new Uint8Array(await img.arrayBuffer()));
console.log(JSON.stringify({result:'inspected',canonical_files_changed:0,rows:f.before.length-1}));
}else if(process.argv.includes('--apply')){
const proof={result:'passed',new_ids:0,source_references_and_versions_preserved:true,files:[],...plan.summary};
for(const f of plan.files){
const bytes=await fs.readFile(f.path,'utf8'),wb=await Workbook.fromCSV(bytes.replace(/^\ufeff/,''),{sheetName:'Dados'}),s=wb.worksheets.getItem('Dados');
assert(s.getRangeByIndexes(0,0,f.before.length,f.before[0].length).values.every((r,i)=>r.every((v,c)=>same(v,f.before[i][c]))),'Import altered original text');
s.getRangeByIndexes(0,0,f.after.length,f.after[0].length).values=f.after;
wb.recalculate();
assert(s.getRangeByIndexes(0,0,f.after.length,f.after[0].length).values.every((r,i)=>r.every((v,c)=>same(v,f.after[i][c]))),'Authored values differ');
const result='\ufeff'+f.after.map(r=>r.map(quote).join(',')).join('\r\n')+'\r\n';
const stage=path.join(out,path.basename(f.path)+'.pending');await fs.writeFile(stage,result,'utf8');
proof.files.push({name:path.basename(f.path),before_sha256:f.before_sha256,after_sha256:hash(result),rows:f.after.length-1,columns:f.after[0].length,stage});
}
// Nothing authoritative is overwritten until all imports/writes have been verified.
for(let i=0;i<plan.files.length;i++){
const f=plan.files[i];assert.equal(hash(await fs.readFile(f.path)),f.before_sha256);
try { await fs.access(path.join(out,path.basename(f.path)+'.before')); }
catch { await fs.copyFile(f.path,path.join(out,path.basename(f.path)+'.before')); }
await fs.copyFile(proof.files[i].stage,f.path);
assert.equal(hash(await fs.readFile(f.path)),proof.files[i].after_sha256);
}
const preview=Workbook.create(),s=preview.worksheets.add('Critérios');
const f=plan.files[0],cols=[0,headersIndex(f,'Estado'),headersIndex(f,'Evidência funcional')];
const changed=f.after.map((r,i)=>({r,i})).filter(({r,i})=>i>0&&JSON.stringify(r)!==JSON.stringify(f.before[i]));
const shown=[...changed.slice(0,3).map(({r})=>r),changed.find(({r})=>r[0]==='AUD-PROFILE-26')?.r||changed[3]?.r];
s.getRange('A1:C5').values=[['ID','Estado','Evidência atual (excerto final)'],...shown.map(r=>cols.map(c=>r[c].slice(-180)))];
s.getRange('A1:C5').format.wrapText=true;s.getRange('A1:C5').format.rowHeightPx=110;
s.getRange('A1:A5').format.columnWidthPx=185;s.getRange('B1:B5').format.columnWidthPx=175;s.getRange('C1:C5').format.columnWidthPx=650;
const img=await preview.render({sheetName:'Critérios',autoCrop:'all',scale:1,format:'png'});
await fs.writeFile(path.join(out,'matrix-current-preview.png'),new Uint8Array(await img.arrayBuffer()));
await fs.writeFile(path.join(out,'csv-authoring-proof.json'),JSON.stringify(proof,null,2));
console.log(JSON.stringify({result:proof.result,requirements:proof.requirements,source_occurrences:proof.source_occurrences,files:proof.files.map(({stage,...v})=>v),states:proof.states}));
}else throw Error('Select inspect or apply');
function headersIndex(f,name){const c=f.before[0].indexOf(name);assert(c>=0);return c;}