from pathlib import Path from datetime import datetime,timezone import importlib.util,json,copy,uuid,hashlib,sys OUT=Path(__file__).resolve().parent;phase=sys.argv[1];oid=int(sys.argv[2]);assert oid in [32,56] spec=importlib.util.spec_from_file_location('transport',OUT/'option-B8-transport.py');lib=importlib.util.module_from_spec(spec);spec.loader.exec_module(lib) state_file=OUT/f'option-B8-documents-{oid}-progress.json';state=json.loads(state_file.read_text(encoding='utf-8'))if state_file.exists()else{'id':oid,'resources':{}} fixtures=json.loads((OUT/'option-B8-fixtures.json').read_text(encoding='utf-8'))['files'] proof={'at':datetime.now(timezone.utc).isoformat(),'phase':phase,'opportunity_id':oid,'target':lib.TARGET,'active_writes':0,'browser_observed':False};clients=[];stage='login';code=1 def save():state_file.write_text(json.dumps(state,ensure_ascii=False,indent=2)+'\n',encoding='utf-8') def view(c):return c.call('GET',f'/minhas-oportunidades/{oid}/view',json_response=False) def action(c,kind,expected=200,**extra):return c.call('POST',f'/minhas-oportunidades/{oid}/workflow',{'etag':view(c)['etag'],'action':kind,'reason':'SIMULAÇÃO QA B8: peças específicas, revisões afetadas e recuperação sem direitos reais',**extra},expected=expected) try: c=lib.Client().login('promoter');clients.append(c) if phase=='upload': assert not state['resources'],'Preserve previously uploaded resources' x=view(c);assert x['workflowState']=='published';state['baseline']=copy.deepcopy(x['values']['canonical']);state['reviews']=copy.deepcopy(x['profileContext']['reviews']);save();action(c,'request_revision') labels=['land-holder','land-minutes','land-map']if oid==32 else['franchise-license','jpeg','docx','xlsx'] for label in labels: stage='upload_'+label;f=fixtures[label];key=str(uuid.uuid4());state.setdefault('creation_keys',{})[label]=key;save() data={'etag':view(c)['etag'],'creation_key':key,'reason':'SIMULAÇÃO QA B8: documento próprio por finalidade, original anterior preservado','payload':json.dumps({'title':'SIMULAÇÃO QA B8 - '+label,'category':'qa-synthetic','classification':'restricted','visibility':'internal','supported_statement':'Peça sintética para o contrato existente; sem validade jurídica.'})} r=c.call('POST',f'/minhas-oportunidades/{oid}/resources/documents',data,expected=201,file=f['path']) row=next(x for x in c.call('GET',f'/minhas-oportunidades/{oid}/resources',json_response=False)['resources']['documents']if x['id']==r['id']) assert row['file']['sha256']==f['sha256'];state['resources'][label]={'resource_id':r['id'],'document_id':row['document_id'],'sha256':f['sha256'],'fixture':f['path']};save() c.call('GET',f'/minhas-oportunidades/{oid}/resources/documents/{r["id"]}/download',expected=423) # Same bytes must not create a second resource/document, even with another key. data['etag']=view(c)['etag'];data['creation_key']=str(uuid.uuid4());c.call('POST',f'/minhas-oportunidades/{oid}/resources/documents',data,expected=422,file=f['path']) proof.update(result='awaiting_own_scan',resources={k:{a:b for a,b in v.items()if a!='fixture'}for k,v in state['resources'].items()},duplicate_bytes_rejected=422,quarantine_denied=423);code=0 elif phase in ['finish','resolve']: assert oid==32 and state['materiality']['reopened'];x=view(c);assert x['workflowState']=='in_review' canonical=state['canonical'];mat=state['materiality'];v=lib.Client().login('validator');clients.append(v);x=view(v) pending=[g for g in mat['reopened']if x['profileContext']['reviews'].get(g,{}).get('decision')!='approved' or any(r.get('gate')==g and r.get('status')!='resolved'for r in x['profileContext']['conditions'].values())] assert pending, 'No repeated finished reviews or resolved conditions' for gate in pending: conditions=[k for k,r in x['profileContext']['conditions'].items()if r.get('gate')==gate and r.get('status')!='resolved'] action(v,'review_gate',gate=gate,gate_decision='approved',evidence_document_ids=[r['resource_id']for r in state['resources'].values()],resolve_condition_ids=conditions) action(v,'approve');pub=lib.Client().login('publisher');clients.append(pub);action(pub,'publish',confirm_publication=True,preview_hash=view(pub)['profileContext']['approval']['hash']) c.logout();clients.remove(c);c=lib.Client().login('promoter');clients.append(c);x=view(c);assert x['workflowState']=='published'and x['values']['canonical']==canonical and x['profileContext']['publication']['visibility']=='internal';c.call('GET',f'/minhas-oportunidades/{oid}/response') proof.update(result='passed',materiality={'reopened':mat['reopened'],'retained':mat['retained']},only_pending_reviews_completed=pending,existing_conditions_explicitly_resolved=True,independent_approval_actor=24,publisher=25,visibility='internal',new_session_contract_recovered=True,Response_recovered=True,original_documents_still_linked=all(d in canonical['documents']for d in state['baseline']['documents']),not_applicable={'resolution_document':'overlaps_conflicts.type=none','exploitation_plan':'exploitation_plan_required=false'});code=0 elif phase=='review': x=view(c);assert x['workflowState']=='needs_information';canonical=copy.deepcopy(x['values']['canonical']) if oid==32: canonical['land_rights']['holder_document_id']=state['resources']['land-holder']['resource_id'] canonical['land_rights']['community_consultation'].update(minutes_document_id=state['resources']['land-minutes']['resource_id'],map_document_id=state['resources']['land-map']['resource_id']) else:canonical['business_transaction']['franchise_terms']['brand_license_document_id']=state['resources']['franchise-license']['resource_id'] canonical['documents']=list(dict.fromkeys([*canonical['documents'],*(r['resource_id']for r in state['resources'].values())])) stage='save_submit';c.call('PUT',f'/minhas-oportunidades/{oid}/draft',{'etag':x['etag'],'canonical':canonical,'reason':'SIMULAÇÃO QA B8: ligar peças identificadas, conservando campos e originais anteriores'}) assert view(c)['values']['canonical']==canonical;state['canonical']=canonical;save();action(c,'submit');x=view(c);mat=x['profileContext']['materiality'];state['materiality']=mat;save() # QA32 also has the explicit territorial/area correction recorded in the same increment. expected={'cadastral_screening','land_legal_review','community_environment_review','competent_authority_clearance'}if oid==32 else{'brand_license_review','franchise_legal_review'} assert set(mat['reopened'])==expected for g in mat['retained']:assert all(x['profileContext']['reviews'][g][k]==state['reviews'][g][k]for k in ['hash','actor_id','at']) v=lib.Client().login('validator');clients.append(v);action(v,'start_review');action(v,'approve',expected=422) ids=[r['resource_id']for r in state['resources'].values()] for gate in mat['reopened']:action(v,'review_gate',gate=gate,gate_decision='approved',evidence_document_ids=ids) action(v,'approve');pub=lib.Client().login('publisher');clients.append(pub);action(pub,'publish',confirm_publication=True,preview_hash=view(pub)['profileContext']['approval']['hash']) c.logout();clients.remove(c);c=lib.Client().login('promoter');clients.append(c);x=view(c);assert x['values']['canonical']==canonical and x['workflowState']=='published'and x['profileContext']['publication']['visibility']=='internal' response=c.call('GET',f'/minhas-oportunidades/{oid}/response');assert response proof.update(result='passed',materiality={'reopened':mat['reopened'],'retained':mat['retained'],'retained_hash_actor_time':True},independent_approval_actor=24,publisher=25,visibility='internal',new_session_contract_recovered=True,Response_recovered=True,original_documents_still_linked=all(d in canonical['documents']for d in state['baseline']['documents'])) if oid==32:proof['not_applicable']={'resolution_document':'overlaps_conflicts.type=none','exploitation_plan':'exploitation_plan_required=false'} else:assert canonical['business_transaction']['franchise_terms']['initial_fee']==1250;proof['financial_terms_preserved']=True code=0 else:raise RuntimeError('Unsupported phase') except Exception as e:proof.update(result='stopped',stage=stage,error_type=type(e).__name__) finally: for c in clients: try:c.logout() except Exception:pass proof['requests']=lib.events;dest=OUT/f'option-B8-documents-{oid}-{phase}-HTTP.json';assert not dest.exists();dest.write_text(json.dumps(proof,ensure_ascii=False,indent=2)+'\n',encoding='utf-8');print(json.dumps({k:v for k,v in proof.items()if k!='requests'},ensure_ascii=False)) raise SystemExit(code)