transaction(function()use($host,$p,&$count){$old=$host->selectOne("SELECT pg_get_constraintdef(oid) d FROM pg_constraint WHERE conrelid='permission_grants'::regclass AND conname='permission_grants_scope_check'")->d;if(!str_contains($old,'fiscal_rules.view')){if(!preg_match('/^CHECK \((.*)\)$/s',$old,$m))throw new LogicException('Unknown scope check');$host->statement('ALTER TABLE permission_grants DROP CONSTRAINT permission_grants_scope_check');$host->statement('ALTER TABLE permission_grants ADD CONSTRAINT permission_grants_scope_check CHECK (('.$m[1].") OR (unit_id IS NOT NULL AND permission IN('fiscal_rules.view','fiscal_rules.prepare','fiscal_rules.review'))) ");}foreach($p['grants_per_book']as$g){if(!in_array($g['user_id'],[13,14,15,16,17],true)||array_intersect_key($g,array_flip(['tenant_id','company_id','unit_id']))!==['tenant_id'=>1,'company_id'=>2,'unit_id'=>2])throw new LogicException('Exact QA recipients');if($host->table('permission_grants')->where($g)->exists())continue;$host->table('permission_grants')->insert($g);App\Modules\Identity\Services\Audit::record('access.granted_on_creation',null,1,2,2,$g['user_id'],['permission'=>$g['permission'],'reason'=>$p['authorization']]);$count++;}if(!$host->getSchemaBuilder()->hasTable('fr_events'))$host->unprepared(file_get_contents(dirname(__DIR__).'/database/sql/fiscal_rules.sql'));});file_put_contents($work.'/fiscal-rules-setup.json',json_encode(['passed'=>true,'book'=>$book,'new_grants'=>$count,'new_right_names'=>3,'new_users'=>0,'new_pg_roles'=>0,'new_demo'=>false],JSON_PRETTY_PRINT));echo json_encode(['passed'=>true,'book'=>$book,'new_grants'=>$count,'proof'=>$work.'/fiscal-rules-setup.json']).PHP_EOL;