-- Prism: rebuild draft final cards from audited models. -- Only quality_status=product, specs>=5, notes>=3, latest note_audit.ok=true. -- State is draft_ready: nothing is auto-published. begin; insert into prism.final_cards(model_id,state,card,prepared_at) select m.id,'draft_ready', jsonb_build_object( 'name',m.name,'vendor',m.vendor,'role',m.role,'domain',m.domain, 'specs',coalesce((select jsonb_agg(jsonb_build_object('key',sp.key,'value',sp.value_text,'unit',sp.unit) order by sp.key) from prism.specs sp where sp.model_id=m.id),'[]'::jsonb), 'notes',coalesce((select jsonb_agg(jsonb_build_object('kind',n.kind,'text',n.text) order by n.kind) from prism.model_notes n where n.model_id=m.id),'[]'::jsonb), 'audit',coalesce((select jsonb_build_object('ok',a.ok,'issues',a.issues) from prism.note_audits a where a.model_id=m.id order by a.id desc limit 1),'{"ok":false,"issues":[]}'::jsonb) ),now() from prism.models m where m.quality_status='product' and (select count(*) from prism.specs sp where sp.model_id=m.id)>=5 and (select count(*) from prism.model_notes n where n.model_id=m.id)>=3 and (select a.ok from prism.note_audits a where a.model_id=m.id order by a.id desc limit 1) is true and not exists (select 1 from prism.final_cards f where f.model_id=m.id); commit;