from pathlib import Path from datetime import datetime,timezone import importlib.util,json OUT=Path(__file__).resolve().parent spec=importlib.util.spec_from_file_location('transport',OUT/'consumer-lot-lib.py') lib=importlib.util.module_from_spec(spec);spec.loader.exec_module(lib) oid=33;progress=OUT/'option-B-public-maturity-progress.json' state=json.loads(progress.read_text(encoding='utf-8'))if progress.exists()else{'opportunity_id':oid,'completed_stages':[]} proof={'at':datetime.now(timezone.utc).isoformat(),'scope':'B','case':'C139','target':lib.TARGET, 'opportunity_id':oid,'active_writes':0,'browser_observed':False,'stages':[]} clients=[];step='login';code=1 def view(c):return c.call('GET',f'/minhas-oportunidades/{oid}/view',json_response=False) def action(c,kind,expected=200,**extra): x=view(c) return c.call('POST',f'/minhas-oportunidades/{oid}/workflow',{'etag':x['etag'],'action':kind, 'reason':'SIMULAÇÃO QA B: maturidade V2 publicada pelo workflow, preservando o catálogo histórico e dados privados',**extra},expected=expected) try: owner=lib.Client().login('promoter');clients.append(owner) validator=lib.Client().login('validator');clients.append(validator) publisher=lib.Client().login('publisher');clients.append(publisher) anon=lib.Client() metadata=anon.call('GET','/api/v1/investment/references')['maturityCatalogue'] assert metadata['version']=='spec-v2'and metadata['legacyVersion']=='legacy-v1' assert len(metadata['stages'])==8 and len(metadata['legacyLabels'])==6 for stage,level,label in [('implementation',7,'Implementação'),('operational',8,'Operacional')]: if stage in state['completed_stages']:continue step='specific_stage_'+stage x=view(owner);assert x['workflowState'] in ['published','needs_information'] and x['profileContext']['publication']['visibility']=='public' baseline=x['profileContext']['reviews'] if x['workflowState']=='published':action(owner,'request_revision') x=view(owner);canonical=x['values']['canonical'] state['pending_stage']=stage state['baseline_reviews']={g:{k:r.get(k)for k in ['hash','actor_id','at']}for g,r in baseline.items()} progress.write_text(json.dumps(state,indent=2)+'\n',encoding='utf-8') canonical['maturity_stage']=stage if 'QA'not in canonical['official_title'].upper()and'SIMULA'not in canonical['official_title'].upper(): canonical['official_title']=canonical['official_title']+' — SIMULAÇÃO QA B' owner.call('PUT',f'/minhas-oportunidades/{oid}/draft',{'etag':x['etag'],'canonical':canonical, 'reason':'Etapa V2 explícita no cenário QA, sem reinterpretar posições históricas ou expor documentos'}) action(owner,'submit');x=view(owner);materiality=x['profileContext']['materiality'] assert materiality['reopened']==[] for gate in materiality['retained']: assert all(x['profileContext']['reviews'][gate][key]==baseline[gate][key]for key in ['hash','actor_id','at']) action(validator,'start_review');action(validator,'approve') action(publisher,'publish',confirm_publication=True,preview_hash=view(publisher)['profileContext']['approval']['hash']) listed=anon.call('GET',f'/api/v1/investment/search?maturity_level={level}&opportunity_id={oid}&include_national=1') assert listed['total']==1 and listed['data'][0]['id']==oid public=listed['data'][0] assert int(public['maturity_level'])==level and public['maturity_label']==label assert public['maturity_catalogue_version']=='spec-v2' assert not set(public).intersection({'management_draft','workflow_context','owner_user_id','organization_id'}) detail=anon.call('GET','/api/v1/investment/opportunities/'+public['slug']) detail_record=detail.get('record',detail.get('opportunity',detail)) assert int(detail_record['maturity_level'])==level and detail_record['maturity_label']==label current=view(owner) assert current['values']['canonical']['maturity_stage']==stage assert current['profileContext']['publication']['maturity']['catalogue_version']=='spec-v2' proof['stages'].append({'stage':stage,'level':level,'label':label,'filter_matches':1, 'public_detail_matches':True,'approved_by':24,'published_by':25,'visibility':'public', 'retained_reviews':materiality['retained'],'original_review_hash_actor_time_preserved':True, 'private_fields_not_serialized':True,'public_slug':public['slug']}) state['completed_stages'].append(stage);state['public_slug']=public['slug'] progress.write_text(json.dumps(state,indent=2)+'\n',encoding='utf-8') for level in [0,9]:anon.call('GET',f'/api/v1/investment/search?maturity_level={level}',expected=422) owner.logout();clients.remove(owner) recovered=lib.Client().login('promoter');clients.append(recovered) x=view(recovered);assert x['values']['canonical']['maturity_stage']=='operational' assert x['profileContext']['publication']['maturity']['level']==8 proof['new_session_recovers_stage_and_version']=True proof['result']='passed';code=0 except Exception as error: proof.update(result='stopped',step=step,error_type=type(error).__name__) finally: for client in clients: try:client.logout() except Exception:pass proof['requests']=lib.events (OUT/'option-B-public-maturity-workflow-HTTP.json').write_text(json.dumps(proof,ensure_ascii=False,indent=2)+'\n',encoding='utf-8') print(json.dumps({key:value for key,value in proof.items()if key!='requests'})) raise SystemExit(code)