Files
Investidor-V2/outputs/investmoz-editorial-QA-20261018/implement.py
T
nala cf003c8623
tests / ci (push) Canceled after 0s
versao nrgocios 4
2026-10-18 15:57:06 +02:00

112 lines
12 KiB
Python

from pathlib import Path
q=Path('C:/Users/macbook/.config/investmoz/editorial-QA-20261018/source')
def edit(name,old,new):
p=q/name;s=p.read_text('utf8');assert old in s,name;p.write_text(s.replace(old,new,1),'utf8')
edit('app/Http/Controllers/PortalManagementController.php',"'is_active' => ['required', 'boolean'],","'is_active' => ['required', 'boolean'],\n 'editorial_published' => ['required', 'boolean'],")
edit('app/Http/Controllers/PortalManagementController.php'," $data = $request->validate($rules);"," $data = $request->validate($rules);\n if ($resource === 'sectors') {\n $data['published_at'] = $data['editorial_published'] ? ($record->published_at ?? now()) : null;\n unset($data['editorial_published']);\n }")
edit('resources/js/pages/management/editor.tsx'," if (isSector) initial.is_active = Boolean(record?.is_active ?? true);"," if (isSector) {\n initial.is_active = Boolean(record?.is_active ?? true);\n initial.editorial_published = Boolean(record?.published_at);\n }")
# Add an explicit publication choice next to the existing sector fields.
edit('resources/js/pages/management/editor.tsx',' {Object.entries(fields).map', ''' {isSector && <Field label="Publicar no catálogo" error={form.errors.editorial_published}>
<label className="flex gap-2"><input type="checkbox" checked={Boolean(form.data.editorial_published)} onChange={e => form.setData('editorial_published', e.target.checked)} />Publicado na navegação e nos filtros públicos quando também estiver activo</label>
<p>Desmarque para retirar do catálogo, conservando o cadastro e as relações.</p>
</Field>}
{Object.entries(fields).map''')
m=q/'database/migrations/2026_10_18_160000_add_portal_editorial_content.php'
m.write_text('''<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
return new class extends Migration {
public function up(): void { Schema::table('portal_resources', fn(Blueprint $t) => $t->jsonb('editorial_content')->nullable()); }
public function down(): void {
if(DB::table('portal_resources')->whereNotNull('editorial_content')->exists()) throw new RuntimeException('Preserve editorial bodies and history before rollback.');
Schema::table('portal_resources', fn(Blueprint $t) => $t->dropColumn('editorial_content'));
}
};
''','utf8')
edit('routes/web.php'," Route::get('/management/portal-services',",''' Route::get('/management/portal-services/resources/{id}/article', [\\App\\Http\\Controllers\\EditorialArticleController::class, 'edit'])->whereNumber('id')->name('editorial.edit');
Route::put('/management/portal-services/resources/{id}/article', [\\App\\Http\\Controllers\\EditorialArticleController::class, 'save'])->whereNumber('id')->name('editorial.save');
Route::get('/management/portal-services',''')
edit('routes/web.php',"Route::get('/carteira',",'''Route::get('/artigos/{id}', [\\App\\Http\\Controllers\\EditorialArticleController::class, 'show'])->whereNumber('id')->name('editorial.show');
Route::get('/carteira',''')
edit('resources/js/pages/portal/manage.tsx',' Editar metadados\n </button>',''' Editar metadados
</button>
<a className={button} href={`/management/portal-services/resources/${r.id}/article`}>Editar artigo</a>''')
controller=r'''<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use App\Services\VerifiedDocumentBinary;
class EditorialArticleController extends Controller
{
private function installed(): void { abort_unless(Schema::hasColumn('portal_resources','editorial_content'),503,'Editor editorial ainda não instalado.'); }
private function publicResources() {
return DB::table('portal_resources as r')->join('documents as d','d.id','=','r.document_id')
->where('r.published',true)->where('r.rights_status','authorized')->where('d.rights_status','authorized')
->where('d.status','active')->where('d.data_classification','public')->whereNull('d.deleted_at')
->where('d.malware_scan_status','clean')->whereColumn('d.sha256','d.malware_scanned_sha256');
}
public function edit(int $id) {
$this->installed();$r=DB::table('portal_resources')->find($id);abort_unless($r,404);
$content=$r->editorial_content?json_decode($r->editorial_content,true):null;
return Inertia::render('portal/article-editor',['resource'=>['id'=>$r->id,'title'=>$r->title,'metadata_version'=>$r->metadata_version],
'content'=>$content,'images'=>$this->publicResources()->whereIn('d.media_type',['image/png','image/jpeg','image/webp'])->get(['r.id','r.title']),
'revisions'=>DB::table('portal_resource_revisions')->where('resource_id',$id)->orderByDesc('revision_no')->get(['revision_no','change_type','created_at'])]);
}
public function save(Request $request,int $id) {
$this->installed();$data=$request->validate(['body'=>['required','string','max:100000'],'image_resource_id'=>['nullable','integer'],'metadata_version'=>['required','integer','min:1']]);
DB::transaction(function()use($request,$id,$data){
$r=DB::table('portal_resources')->where('id',$id)->lockForUpdate()->first();abort_unless($r,404);
abort_unless((int)$r->metadata_version===(int)$data['metadata_version'],409,'O artigo foi alterado noutra sessão. Recarregue antes de editar.');
if(!empty($data['image_resource_id'])) abort_unless($this->publicResources()->where('r.id',$data['image_resource_id'])->whereIn('d.media_type',['image/png','image/jpeg','image/webp'])->exists(),422,'Escolha uma imagem pública disponível na biblioteca.');
$body=trim($data['body']);if($body==='')throw ValidationException::withMessages(['body'=>'Escreva o corpo do artigo.']);
$content=['format'=>1,'body'=>$body,'image_resource_id'=>$data['image_resource_id']??null];
$revision=(int)$r->metadata_version+1;
DB::table('portal_resources')->where('id',$id)->update(['editorial_content'=>json_encode($content,JSON_THROW_ON_ERROR),'published'=>false,'approved_by'=>null,'metadata_version'=>$revision,'last_reviewed_by'=>$request->user()->id,'last_reviewed_at'=>now(),'updated_at'=>now()]);
$resource=DB::table('portal_resources')->find($id);$links=DB::table('portal_resource_links')->where('resource_id',$id)->orderBy('id')->get();
DB::table('portal_resource_revisions')->insert(['resource_id'=>$id,'revision_no'=>$revision,'change_type'=>'editorial_updated','snapshot'=>json_encode(['resource'=>$resource,'associations'=>$links],JSON_THROW_ON_ERROR),'actor_user_id'=>$request->user()->id,'created_at'=>now()]);
DB::table('audit_events')->insert(['source_system'=>'portal-management','actor_user_id'=>$request->user()->id,'entity_type'=>'portal_resources','entity_id'=>null,'action'=>'editorial_updated','before_data'=>json_encode(['record_id'=>$id,'metadata_version'=>$r->metadata_version]),'after_data'=>json_encode(['record_id'=>$id,'metadata_version'=>$revision,'published'=>false])]);
});
return redirect('/management/portal-services/resources/'.$id.'/article')->with('success','Artigo guardado como rascunho. Publique expressamente no acervo quando estiver pronto.');
}
public function show(int $id) {
$this->installed();$r=$this->publicResources()->where('r.id',$id)->first(['r.id','r.title','r.description','r.editorial_content','r.document_id','d.issuer']);
abort_unless($r && $r->editorial_content,404);$content=json_decode($r->editorial_content,true);
// Recheck the original bytes using the same binary gate as the library.
$binary=app(VerifiedDocumentBinary::class)->respond($this->publicResources()->where('r.id',$id)->first(['r.*','d.*']));
$image=!empty($content['image_resource_id'])?$this->publicResources()->where('r.id',$content['image_resource_id'])->whereIn('d.media_type',['image/png','image/jpeg','image/webp'])->value('r.id'):null;
return Inertia::render('portal/article',['article'=>['id'=>$id,'title'=>$r->title,'description'=>$r->description,'author'=>$r->issuer,'body'=>$content['body'],'image_url'=>$image?'/documentos/'.$image.'/view':null,'original_url'=>'/documentos/'.$id]]);
}
}
'''
(q/'app/Http/Controllers/EditorialArticleController.php').write_text(controller,'utf8')
(q/'resources/js/pages/portal/article-editor.tsx').write_text('''import { Link, useForm } from '@inertiajs/react';
import { Management, Field, button, control } from '../management/shared';
type Content = { body: string; image_resource_id: number | null };
export default function ArticleEditor({resource, content, images, revisions}: {resource:{id:number;title:string;metadata_version:number};content:Content|null;images:{id:number;title:string}[];revisions:{revision_no:number;change_type:string;created_at:string}[]}) {
const form=useForm({body:content?.body??'',image_resource_id:content?.image_resource_id?String(content.image_resource_id):'',metadata_version:resource.metadata_version});
return <Management title={`Editar artigo — ${resource.title}`}><p>O original permanece intacto na biblioteca. Guardar o corpo retira a publicação até à sua ação expressa no acervo.</p>
<form className="max-w-3xl space-y-5" onSubmit={e=>{e.preventDefault();form.put(`/management/portal-services/resources/${resource.id}/article`);}}>
<Field label="Corpo do artigo" error={form.errors.body}><textarea className={control} rows={16} value={form.data.body} onChange={e=>form.setData('body',e.target.value)} /><p>Texto simples. Separe os parágrafos com uma linha em branco.</p></Field>
<Field label="Imagem da biblioteca" error={form.errors.image_resource_id}><select className={control} value={form.data.image_resource_id} onChange={e=>form.setData('image_resource_id',e.target.value)}><option value="">Sem imagem</option>{images.map(i=><option key={i.id} value={i.id}>{i.title}</option>)}</select></Field>
<button className={button} disabled={form.processing}>Guardar artigo como rascunho</button> <Link className="underline" href="/management/portal-services">Voltar ao acervo</Link>
</form><h2>Histórico</h2><ul>{revisions.map(r=><li key={r.revision_no}>Revisão {r.revision_no} · {r.change_type} · {r.created_at}</li>)}</ul>
<p>Título, descrição, autor e fonte são editados em Editar metadados no acervo.</p></Management>;
}
''','utf8')
(q/'resources/js/pages/portal/article.tsx').write_text('''import { Head, Link } from '@inertiajs/react';
import { PortalMenu } from '@/layouts/portal-navigation';
export default function Article({article}:{article:{id:number;title:string;description:string|null;author:string|null;body:string;image_url:string|null;original_url:string}}) {
return <><Head title={article.title}/><PortalMenu/><main className="mx-auto max-w-3xl space-y-6 p-6"><h1 className="text-3xl font-bold">{article.title}</h1>{article.description&&<p>{article.description}</p>}{article.author&&<p>Autor / entidade: {article.author}</p>}{article.image_url&&<img src={article.image_url} alt="Imagem do artigo"/>}<article className="space-y-5">{article.body.split(/\\n\\s*\\n/).map((p,i)=><p className="whitespace-pre-wrap" key={i}>{p}</p>)}</article><Link href={article.original_url} className="underline">Consultar documento original</Link><p><Link href="/documentos" className="underline">Voltar à biblioteca</Link></p></main></>;
}
''','utf8')
# Discover the public adaptation from the existing document detail without leaking its body/metadata in the list.
edit('resources/js/pages/portal/document.tsx',' <article className=', ''' <Link className="underline" href={`/artigos/${resource.id}`}>Consultar adaptação editorial, quando disponível</Link>
<article className=''')
print('QA-only editorial delta written; active source untouched')