# Instalador/configurador do Trivio PDV+ via API direta (sem UI Automation). # Servido via "irm https://mesh.grupobona.com.br | iex" - roda 100% em memoria, # nenhum arquivo .ps1/.cmd/.bat fica na maquina. Este script NAO tem nenhuma # credencial: a assinatura Hubee (HMAC) e calculada no proprio servidor # (mesh.grupobona.com.br/merchants/{cnpj}, ver trivio-signer-server.js), que # repassa a chamada assinada pra api.triv.io e devolve so o resultado. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $script:SignerBaseUrl = 'https://mesh.grupobona.com.br' $script:InstallerUrl = 'https://trivio-arquivos.s3.amazonaws.com/pdvreader/Instalador%20PDV%2B.exe' $script:InstallDir = 'C:\TrivioCRM\PDV+' function Test-Cnpj { param([string]$Value) $digits = ($Value -replace '\D', '') if ($digits.Length -ne 14) { return $false } if ($digits -match '^(\d)\1{13}$') { return $false } $calc = { param($nums, $weights) $sum = 0 for ($i = 0; $i -lt $nums.Length; $i++) { $sum += [int]::Parse($nums[$i]) * $weights[$i] } $rest = $sum % 11 if ($rest -lt 2) { return 0 } else { return 11 - $rest } } $d1 = & $calc $digits[0..11] @(5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2) $d2 = & $calc $digits[0..12] @(6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2) return ($digits[12] -eq [string]$d1) -and ($digits[13] -eq [string]$d2) } # A assinatura Hubee acontece no servidor (mesh.grupobona.com.br/merchants/{cnpj} # -> trivio-signer-server.js -> api.triv.io). Este script so fala com o nosso # proprio dominio, nunca tem o ClientSecret em maos. function Get-TrivioMerchant { param([string]$CnpjDigits) $fullUrl = "$script:SignerBaseUrl/merchants/$CnpjDigits" try { return Invoke-RestMethod -Uri $fullUrl -Method Get -ErrorAction Stop } catch { $resp = $_.Exception.Response if ($resp -and [int]$resp.StatusCode -eq 404) { return $null } throw } } function Get-ErpOrdinal { param([string]$NameErp) $key = '' if ($NameErp) { $key = $NameErp.Trim().ToLowerInvariant() } switch ($key) { 'sistemabig' { return 0 } 'alpha7' { return 1 } 'pontosys' { return 2 } 'automatiza' { return 3 } 'softpharma' { return 4 } 'vetor' { return 5 } default { return 0 } } } function Stop-TrivioProcess { Get-Process -Name 'TrivioPDV+' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue $deadline = (Get-Date).AddSeconds(10) while ((Get-Date) -lt $deadline) { if (-not (Get-Process -Name 'TrivioPDV+' -ErrorAction SilentlyContinue)) { break } Start-Sleep -Milliseconds 200 } Start-Sleep -Seconds 2 } function Install-TrivioExe { $exePath = Join-Path $script:InstallDir 'TrivioPDV+.exe' if (Test-Path $exePath) { return $exePath } $installerPath = Join-Path $env:TEMP 'InstaladorPDV+.exe' Write-Host 'Baixando instalador oficial...' -ForegroundColor Cyan Invoke-WebRequest -Uri $script:InstallerUrl -OutFile $installerPath -UseBasicParsing Write-Host 'Instalando (silencioso)...' -ForegroundColor Cyan $proc = Start-Process -FilePath $installerPath -ArgumentList '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/SP-' -PassThru -Wait if ($proc.ExitCode -ne 0) { throw "Instalador retornou codigo $($proc.ExitCode)." } if (-not (Test-Path $exePath)) { throw "Instalacao concluida mas '$exePath' nao foi encontrado." } # O instalador (secao [Run] do Inno Setup) abre o app sozinho ao terminar; # encerra pra controlarmos o fluxo a partir daqui. Start-Sleep -Seconds 2 Stop-TrivioProcess Remove-Item $installerPath -Force -ErrorAction SilentlyContinue return $exePath } function Set-TrivioConfig { param($Merchant, [string]$CnpjDigits) New-Item -ItemType Directory -Force -Path $script:InstallDir | Out-Null # Mesmos nomes de propriedade de trivio_PdvReader_App.Core.Shared.ValueObjects.Merchant $merchantOut = [ordered]@{ LegalName = $Merchant.legalName CompanyName = $Merchant.companyName Alias = $Merchant.alias Cnpj = $Merchant.cnpj Address = $Merchant.address Number = $Merchant.number Neighborhood = $Merchant.neighborhood City = $Merchant.city Uf = $Merchant.uf EconomicGroupId = $Merchant.economicGroupId MerchantId = $Merchant.merchantId NameErp = $Merchant.nameErp TimeZone = $Merchant.timeZone } ($merchantOut | ConvertTo-Json) | Set-Content -Path (Join-Path $script:InstallDir 'MerchantConfig.json') -Encoding UTF8 # So os campos que afetam o boot (ver FormConfig.btnSave_Click); o resto # fica nos defaults de ConfigValueObject e pode ser revisto depois no # proprio menu "Configuracoes" do PDV+. $configOut = [ordered]@{ Cnpj = $CnpjDigits Erp = Get-ErpOrdinal -NameErp $Merchant.nameErp } ($configOut | ConvertTo-Json) | Set-Content -Path (Join-Path $script:InstallDir 'PdvReaderConfig.json') -Encoding UTF8 } function Invoke-TrivioInstallAndConfigure { param([string]$CnpjDigits) Write-Host 'Consultando CNPJ na API da Trivio...' -ForegroundColor Cyan $merchant = $null try { $merchant = Get-TrivioMerchant -CnpjDigits $CnpjDigits } catch { Write-Host "Erro ao consultar a API da Trivio: $($_.Exception.Message)" -ForegroundColor Red; return } if (-not $merchant) { Write-Host 'CNPJ nao cadastrado na Trivio. Entre em contato com o suporte.' -ForegroundColor Red; return } $exePath = $null try { $exePath = Install-TrivioExe } catch { Write-Host "Erro ao instalar o PDV+: $($_.Exception.Message)" -ForegroundColor Red; return } Stop-TrivioProcess Set-TrivioConfig -Merchant $merchant -CnpjDigits $CnpjDigits Write-Host 'PDV+ configurado com sucesso (sem automacao de UI).' -ForegroundColor Green Write-Host " Loja: $($merchant.companyName)" Write-Host " Razao social: $($merchant.legalName)" Write-Host " MerchantId: $($merchant.merchantId)" Write-Host " EconomicGroupId: $($merchant.economicGroupId)" Write-Host " ERP integrado: $($merchant.nameErp)" Write-Host 'Iniciando TrivioPDV+.exe...' -ForegroundColor Cyan Start-Process -FilePath $exePath -WorkingDirectory (Split-Path $exePath) } function Invoke-TrivioLookup { param([string]$CnpjDigits) try { $merchant = Get-TrivioMerchant -CnpjDigits $CnpjDigits } catch { Write-Host "Erro ao consultar a API da Trivio: $($_.Exception.Message)" -ForegroundColor Red; return } if (-not $merchant) { Write-Host 'CNPJ nao encontrado na Trivio.' -ForegroundColor Red; return } Write-Host "Loja: $($merchant.companyName)" Write-Host "Razao social: $($merchant.legalName)" Write-Host "MerchantId: $($merchant.merchantId)" Write-Host "EconomicGroupId: $($merchant.economicGroupId)" Write-Host "ERP integrado: $($merchant.nameErp)" } function Invoke-TrivioUninstall { Stop-TrivioProcess $uninstaller = Join-Path $script:InstallDir 'unins000.exe' if (Test-Path $uninstaller) { Write-Host 'Rodando desinstalador oficial...' -ForegroundColor Cyan Start-Process -FilePath $uninstaller -ArgumentList '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/SP-' -Wait } if (Test-Path $script:InstallDir) { Remove-Item $script:InstallDir -Recurse -Force -ErrorAction SilentlyContinue } $identityDir = Join-Path $env:ProgramData 'Trivio' if (Test-Path $identityDir) { Remove-Item $identityDir -Recurse -Force -ErrorAction SilentlyContinue } try { Unregister-ScheduledTask -TaskName 'TrivioPDV+' -Confirm:$false -ErrorAction Stop } catch {} try { sc.exe delete TrivioPdvPlusStarter | Out-Null } catch {} Write-Host 'Limpeza concluida (alguns itens podem exigir execucao como Administrador).' -ForegroundColor Yellow } function Read-CnpjFromUser { while ($true) { $value = Read-Host 'CNPJ (com ou sem pontuacao)' if (Test-Cnpj $value) { return ($value -replace '\D', '') } Write-Host 'CNPJ invalido (digitos verificadores nao conferem).' -ForegroundColor Red } } function Show-TrivioMenu { Write-Host '' Write-Host '======================================' -ForegroundColor Cyan Write-Host ' Trivio PDV+ - instalador direto' -ForegroundColor Cyan Write-Host '======================================' -ForegroundColor Cyan Write-Host ' 1) Instalar / configurar (CNPJ)' Write-Host ' 2) Consultar CNPJ (somente leitura)' Write-Host ' 3) Desinstalar tudo' Write-Host ' 0) Sair' Write-Host '======================================' -ForegroundColor Cyan } while ($true) { Show-TrivioMenu $opt = Read-Host 'Escolha uma opcao' switch ($opt) { '1' { Invoke-TrivioInstallAndConfigure -CnpjDigits (Read-CnpjFromUser) } '2' { Invoke-TrivioLookup -CnpjDigits (Read-CnpjFromUser) } '3' { Invoke-TrivioUninstall } '0' { return } default { Write-Host 'Opcao invalida.' -ForegroundColor Yellow } } }