commit c9983cbad53269a32df5066497005f0e2d336f03 Author: felipe.franca Date: Tue Nov 17 17:43:00 2026 -0300 181186 - Criar PDV Android para rodar em maquinas P.O.S. diff --git a/pdv/.gitignore b/pdv/.gitignore new file mode 100644 index 0000000..29a3a50 --- /dev/null +++ b/pdv/.gitignore @@ -0,0 +1,43 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/pdv/.metadata b/pdv/.metadata new file mode 100644 index 0000000..3e6e02a --- /dev/null +++ b/pdv/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + base_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + - platform: android + create_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + base_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + - platform: ios + create_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + base_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + - platform: linux + create_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + base_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + - platform: macos + create_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + base_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + - platform: web + create_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + base_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + - platform: windows + create_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + base_revision: 78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/pdv/README.md b/pdv/README.md new file mode 100644 index 0000000..7c4f800 --- /dev/null +++ b/pdv/README.md @@ -0,0 +1,39 @@ +# PDV + +Aplicativo Android de ponto de venda em Flutter, com integração planejada +para Odoo 7 e Odoo 19. A especificação funcional e técnica está no módulo +`pdv_pos` do repositório SigErp. + +## Desenvolvimento + +Requisitos identificados no ambiente: Flutter 3.16.5 e Dart 3.2.3. + +```sh +flutter pub get +flutter run +flutter analyze +flutter test +``` + +### Executar a versão desktop no Linux para desenvolvimento + +O plugin `flutter_secure_storage` compila o backend Linux mesmo que, em debug, +o PDV use armazenamento de sessão em memória. Em Debian/Ubuntu, instale a +dependência de desenvolvimento do libsecret antes de compilar: + +```sh +sudo apt install libsecret-1-dev +flutter pub get +flutter run -d linux +``` + +Fase 0 está concluída e a Fase 1 está em homologação. A configuração é +persistida localmente, o teste de conexão usa `GET /pdv_pos/health` e o login +Odoo 7 valida a licença e autentica o usuário em `POST /pdv_pos/logar`. O login +fora do Android pula a licença do dispositivo para permitir testes desktop, +mas ainda exige usuário Odoo. O login precisa ser homologado no servidor e no +serviço de licenças antes de uso real. + +A Fase 2 começou com a tela de Venda e o catálogo por departamento. A primeira +versão carrega todos os produtos do departamento selecionado sem paginação; +essa decisão será reavaliada com o volume real do catálogo POS. diff --git a/pdv/analysis_options.yaml b/pdv/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/pdv/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/pdv/android/.gitignore b/pdv/android/.gitignore new file mode 100644 index 0000000..6f56801 --- /dev/null +++ b/pdv/android/.gitignore @@ -0,0 +1,13 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app +key.properties +**/*.keystore +**/*.jks diff --git a/pdv/android/app/build.gradle b/pdv/android/app/build.gradle new file mode 100644 index 0000000..c340391 --- /dev/null +++ b/pdv/android/app/build.gradle @@ -0,0 +1,67 @@ +plugins { + id "com.android.application" + id "kotlin-android" + id "dev.flutter.flutter-gradle-plugin" +} + +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +android { + namespace "com.example.pdv" + compileSdkVersion 34 + ndkVersion flutter.ndkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId "com.example.pdv" + // You can update the following values to match your application needs. + // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. + minSdkVersion flutter.minSdkVersion + targetSdkVersion flutter.targetSdkVersion + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig signingConfigs.debug + } + } +} + +flutter { + source '../..' +} + +dependencies {} diff --git a/pdv/android/app/src/debug/AndroidManifest.xml b/pdv/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/pdv/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/pdv/android/app/src/main/AndroidManifest.xml b/pdv/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..0da3b24 --- /dev/null +++ b/pdv/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + diff --git a/pdv/android/app/src/main/kotlin/com/example/pdv/MainActivity.kt b/pdv/android/app/src/main/kotlin/com/example/pdv/MainActivity.kt new file mode 100644 index 0000000..ae1236e --- /dev/null +++ b/pdv/android/app/src/main/kotlin/com/example/pdv/MainActivity.kt @@ -0,0 +1,6 @@ +package com.example.pdv + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() { +} diff --git a/pdv/android/app/src/main/res/drawable-v21/launch_background.xml b/pdv/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/pdv/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/pdv/android/app/src/main/res/drawable/launch_background.xml b/pdv/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/pdv/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/pdv/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/pdv/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..0e5e73b Binary files /dev/null and b/pdv/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/pdv/android/app/src/main/res/mipmap-hdpi/pdv_launcher.png b/pdv/android/app/src/main/res/mipmap-hdpi/pdv_launcher.png new file mode 100644 index 0000000..0e46e9c Binary files /dev/null and b/pdv/android/app/src/main/res/mipmap-hdpi/pdv_launcher.png differ diff --git a/pdv/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/pdv/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..1db5910 Binary files /dev/null and b/pdv/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/pdv/android/app/src/main/res/mipmap-mdpi/pdv_launcher.png b/pdv/android/app/src/main/res/mipmap-mdpi/pdv_launcher.png new file mode 100644 index 0000000..cf8fbad Binary files /dev/null and b/pdv/android/app/src/main/res/mipmap-mdpi/pdv_launcher.png differ diff --git a/pdv/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/pdv/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..0065127 Binary files /dev/null and b/pdv/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/pdv/android/app/src/main/res/mipmap-xhdpi/pdv_launcher.png b/pdv/android/app/src/main/res/mipmap-xhdpi/pdv_launcher.png new file mode 100644 index 0000000..a43d73d Binary files /dev/null and b/pdv/android/app/src/main/res/mipmap-xhdpi/pdv_launcher.png differ diff --git a/pdv/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/pdv/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..13f0bab Binary files /dev/null and b/pdv/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/pdv/android/app/src/main/res/mipmap-xxhdpi/pdv_launcher.png b/pdv/android/app/src/main/res/mipmap-xxhdpi/pdv_launcher.png new file mode 100644 index 0000000..ed8714e Binary files /dev/null and b/pdv/android/app/src/main/res/mipmap-xxhdpi/pdv_launcher.png differ diff --git a/pdv/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/pdv/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..cb9449e Binary files /dev/null and b/pdv/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/pdv/android/app/src/main/res/mipmap-xxxhdpi/pdv_launcher.png b/pdv/android/app/src/main/res/mipmap-xxxhdpi/pdv_launcher.png new file mode 100644 index 0000000..4367fc1 Binary files /dev/null and b/pdv/android/app/src/main/res/mipmap-xxxhdpi/pdv_launcher.png differ diff --git a/pdv/android/app/src/main/res/values-night/styles.xml b/pdv/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/pdv/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/pdv/android/app/src/main/res/values/styles.xml b/pdv/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/pdv/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/pdv/android/app/src/profile/AndroidManifest.xml b/pdv/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/pdv/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/pdv/android/build.gradle b/pdv/android/build.gradle new file mode 100644 index 0000000..e83fb5d --- /dev/null +++ b/pdv/android/build.gradle @@ -0,0 +1,30 @@ +buildscript { + ext.kotlin_version = '1.7.10' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = '../build' +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(':app') +} + +tasks.register("clean", Delete) { + delete rootProject.buildDir +} diff --git a/pdv/android/gradle.properties b/pdv/android/gradle.properties new file mode 100644 index 0000000..598d13f --- /dev/null +++ b/pdv/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx4G +android.useAndroidX=true +android.enableJetifier=true diff --git a/pdv/android/gradle/wrapper/gradle-wrapper.properties b/pdv/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..3c472b9 --- /dev/null +++ b/pdv/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip diff --git a/pdv/android/settings.gradle b/pdv/android/settings.gradle new file mode 100644 index 0000000..7cd7128 --- /dev/null +++ b/pdv/android/settings.gradle @@ -0,0 +1,29 @@ +pluginManagement { + def flutterSdkPath = { + def properties = new Properties() + file("local.properties").withInputStream { properties.load(it) } + def flutterSdkPath = properties.getProperty("flutter.sdk") + assert flutterSdkPath != null, "flutter.sdk not set in local.properties" + return flutterSdkPath + } + settings.ext.flutterSdkPath = flutterSdkPath() + + includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } + + plugins { + id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false + } +} + +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "7.3.0" apply false +} + +include ":app" diff --git a/pdv/assets/icons/icone.png b/pdv/assets/icons/icone.png new file mode 100644 index 0000000..7c4f139 Binary files /dev/null and b/pdv/assets/icons/icone.png differ diff --git a/pdv/docs/API_CONTRACTS.md b/pdv/docs/API_CONTRACTS.md new file mode 100644 index 0000000..946f6e4 --- /dev/null +++ b/pdv/docs/API_CONTRACTS.md @@ -0,0 +1,222 @@ +# Contratos de API + +Ainda não há contrato de operações de negócio confirmado para o PDV. Os +contratos de health check e login Odoo 7 estão definidos abaixo e aguardam +homologação no servidor real. + +O app oferece interfaces `AuthRepository` e `ConnectionTester`; ambas têm +implementações para Odoo 7. Nenhum endpoint de catálogo ou venda foi presumido. + +## API dedicada do PDV + +Foi selecionada a implementação de endpoints próprios no módulo `pdv_pos`. +O primeiro contrato é o health check público e sem dados sensíveis: + +- `GET /pdv_pos/health` +- Sucesso HTTP 200: `{"status":"ok","api_version":1}` +- Não requer autenticação e não retorna dados da empresa, usuário ou banco. +- O app envia essa chamada pelo botão **Testar conexão** e só considera + sucesso quando o status HTTP e o contrato JSON forem válidos. + +O código do controller foi adicionado ao módulo `pdv_pos` e o cliente não +segue redirecionamentos. A rota ainda precisa ser instalada/homologada em um +servidor Odoo 7 real. Esse contrato identifica a versão da API PDV, não a +versão principal do Odoo. + +### Login e sessão Odoo 7 + +O endpoint combinado replica apenas o fluxo pertinente do Coletor — validar a +licença do dispositivo e autenticar o operador — em uma única chamada: + +- `POST /pdv_pos/logar` +- Formulário: `cnpj`, `username`, `password`, `serial`, `model`, `brand` e + `version` do app, mais `platform` (`android`, `linux`, etc.). +- `cnpj` seleciona o database via `app_pdv_pos.config`; `username/password` + são credenciais de `res.users`. +- No Android, o controller exige serial/model/brand, valida a licença do + dispositivo com tipo `3` (PDV) e inicia a sessão web Odoo após a validação. +- Fora do Android, o controller pula a validação de licença para permitir + desenvolvimento desktop; ainda exige credenciais válidas do Odoo. +- Sucesso JSON contém `status`, `user` (`id`, `name`) e `company_id`. O Odoo + emite o cookie HTTP `sid` e retorna o `session_id` interno do Odoo; o app + guarda ambos em armazenamento seguro e nunca persiste a senha. +- Chamadas autenticadas seguintes enviam o cookie `sid` e o parâmetro + `session_id` para restaurar a sessão Odoo 7. +- Cada endpoint protegido verifica a presença de usuário e database na sessão, + sem forçar um novo `common.login`; o RPC Odoo valida a credencial e + `AccessDenied` invalida a sessão. +- `POST /pdv_pos/logout` invalida a sessão; o app envia ambos os valores. + +Os tipos de licença `3` foram adicionados aos modelos locais `valida.dispositivo` +e centrais `contrecf.mobile`, mantendo Coletor (`1`) e Comanda (`2`) separados. +O controller ainda precisa ser instalado e homologado, inclusive contra o +serviço central de licenças. + +O app Android usa `DeviceInfo.id`, `model` e `brand`, seguindo o Coletor. É +necessário confirmar em POS reais se `DeviceInfo.id` é estável e exclusivo o +suficiente para representar o dispositivo/licença. + +`platform` é informado pelo cliente e pode ser falsificado. Portanto, o fluxo +sem licença deve ser usado somente para desenvolvimento; não é prova confiável +de que a requisição veio de um sistema operacional não Android. + +## Inspeção do backend Odoo 7 (código encontrado, ainda não homologado) + +### Clientes e opções de pagamento (Fase 4) + +Foram criadas duas consultas autenticadas no controller PDV: + +- `POST /pdv_pos/clientes` recebe `query` no corpo do formulário e pesquisa em + `financeiro.cliente`, limitada a 50 resultados da empresa padrão do usuário. + A resposta inclui nome e documento mascarado; o documento completo não sai + do Odoo nem é colocado na URL. +- `GET /pdv_pos/formas_pagamento` consulta combinações ativas de + `adm.condicao.forma`, incluindo forma e condição de pagamento. A resposta é + dinâmica; os IDs/tipos retornados não são fixados no app. + +Na interface, os tipos Odoo são agrupados em quatro ações: Dinheiro (`01`), +PIX (`17`, `20`, `23`), Cartão de Crédito (`03`) e Cartão de Débito (`04`). Se +o servidor retornar mais de uma condição para um grupo, o app pede a escolha +entre as condições disponíveis. + +O app permite distribuir o valor entre várias parcelas/formas, sem exceder o +total. Valores em dinheiro são registrados como recebidos na tela; PIX e cartões +permanecem pendentes até confirmação pela API do POS, cujo contrato ainda não +foi fornecido. A finalização de dinheiro usa o endpoint descrito abaixo. O app +exibe número/série da nota e oferece retorno para iniciar nova venda; a +impressão depende da API/SDK do POS. + +### Finalização de venda NFC-e (implementada no addon; pendente de homologação) + +- `POST /pdv_pos/finalizar_venda` recebe `checkout_key`, `items` e `payments` + como JSON no corpo do formulário; também aceita cliente e CPF/CNPJ opcional. +- O endpoint obtém empresa e local padrão da sessão, resolve em lote as + locações/embalagens dos produtos, cria pedido com itens e condições, calcula + parcelas, valida e chama `pedcap_button_faturar_pedido_nfce`, aguardando o + retorno do Odoo/SEFAZ. O app bloqueia as ações durante a chamada e mostra um + indicador de finalização. +- Só aceita formas de pagamento dinheiro (`01`) até integrar a API do POS. + Confere no servidor que as condições estão ativas e que a soma recebida é + igual ao total. +- A `checkout_key` é usada para localizar o mesmo pedido em uma repetição após + timeout, evitando criar outro pedido na mesma sessão de pagamento. +- Se o parâmetro do estoque exigir CPF/CNPJ e não houver cliente, o servidor + retorna `customer_cpf_required` antes de criar o pedido. O app solicita o + documento e repete a chamada. +- Se houver uma NFC-e vinculada ao pedido, o checkout retorna sucesso qualquer + que seja o estado da nota; a resposta traz número/série, estado, número do + pedido e uma mensagem fiscal segura, sem traceback. Notas offline são + identificadas como “Emitida em Contingência”. Sem nota vinculada, o app + libera nova tentativa e mostra uma mensagem de erro, sem permanecer travado. +- O DANFE/NFC-e ainda não é enviado para impressão. A integração escolhida é a + API/SDK da impressora do POS, cujo contrato/modelo precisa ser fornecido. + +### Histórico de vendas + +- `GET /pdv_pos/historico_vendas` retorna os pedidos de venda (`tipo = V`) do + vendedor associado ao usuário autenticado, nos estados validado (`V`) ou + faturado (`F`). Se o pedido não tiver vendedor, só é incluído quando foi + criado pelo usuário autenticado. O vendedor é determinado no servidor, não + aceito como parâmetro do app. +- Cada registro contém número do pedido, data de emissão, nome do cliente + quando houver, total e estado. Pedidos faturados abrem uma confirmação de + reimpressão; a execução da impressão continua pendente da API/SDK do POS. + +### Leitura de código de barras + +- O botão de câmera lê o código e consulta `GET + /pdv_pos/produto_por_codigo_barra`. O endpoint resolve o código de barras + cadastrado para uma grade e devolve o produto com os dados do catálogo de + venda; quando não houver correspondência disponível no catálogo, retorna + `product: null`. +- Ao encontrar o item, o app adiciona uma unidade ao carrinho; caso contrário, + informa o código lido que não foi encontrado. +- As imagens do catálogo são redimensionadas no servidor para até 50 px no + maior lado, preservando a proporção. + +Foi encontrado o módulo `api_sigerp`, com controller em `/apsg` e métodos +`api_logar`, `api_executar` e `api_revalidar_token`. O script de teste do +módulo usa, como exemplo de chamadas, `GET /apsg/api_logar` com os parâmetros +`usuario`, `senha` e `sg_code`; as operações seguintes usam +`/apsg/api_executar` com token no header `Authorization`. O refresh usa +`/apsg/api_revalidar_token` com o parâmetro `token`. + +Esses detalhes são evidência do código legado, não um contrato aprovado para +o PDV. O login legado depende de `sg_code`, que contém base, duração do token e uma +frase secreta codificados. O campo CNPJ/identificador do app não aparece +associado a esse valor. O fluxo genérico também não fornece um endpoint +anônimo de saúde: a ação `tabela=teste` é executada depois da autenticação. + +O módulo `vendas_externas` contém métodos de modelo, não controllers HTTP +específicos do PDV: + +- `vexdep_busca_departamentos(data_sinc_departamento)` devolve departamentos + alterados com código, descrição e departamento pai. +- `vexdep_busca_produtos(company_id, data_sic_prod, foto)` devolve grades de + produtos alteradas com código, descrição, departamento, preço e saldo; a + foto é opcional. O método depende do local configurado no estoque. + +O login agora mantém em memória o `company_id` padrão retornado por `res.users` +em um objeto de sessão, para os casos de uso do catálogo. Isso não define uma +seleção de empresa quando o usuário tem múltiplas empresas. + +Ainda é necessário confirmar como esses métodos devem ser expostos/chamados, +quais permissões são necessárias, o formato de datas, paginação e o contrato +da instalação real. + +Os métodos atuais recebem timestamps de sincronização e não oferecem +`offset`/`limit`. O de produtos procura alterações em todo o estoque local +configurado, portanto não se deve chamá-lo como catálogo paginado sem adaptar +o contrato ou definir cache incremental e carga inicial. + +### Catálogo Odoo 7 (Fase 2) + +Por decisão do responsável, a primeira versão retorna todo o catálogo, sem +paginação: + +- `GET /pdv_pos/departamentos` retorna `departments: [{id, name}]`, ordenados + pelo nome em ordem alfabética. O app mostra somente o nome; `id` serve para + solicitar os produtos do departamento. +- `GET /pdv_pos/produtos_por_departamento?department_id=` retorna + `products` do departamento selecionado, incluindo campos fornecidos por + `vexdep_busca_produtos` e imagens; cada produto agora inclui também `grade_id` + para criar as linhas de pedido sem nova busca por produto. +- O Odoo usa a empresa padrão do usuário autenticado e o local de venda + configurado em Estoque/Vendas Externas. +- A data de sincronização vazia significa carga inicial completa. Não há + `offset`/`limit` nesta versão; rever após medir o tamanho e desempenho do + catálogo real. + +### Backend legado: autenticação e seleção de base + +No backend Odoo 7, o helper `valida.controller.MySock` autentica via +`xmlrpc/common.login(database, user, password)`. O helper também contém um modo +opcional que consulta um arquivo `app.config` para mapear CNPJ para database, +mas não foi encontrado um uso desse modo no fluxo de `api_sigerp` ou em +`vendas_externas`. Portanto, esse código não confirma que o CNPJ do PDV deve +ser usado para selecionar a base. + +O endpoint PDV usa o mapeamento configurado em `app_pdv_pos.config`; a +entrada ainda precisa ser configurada e confirmada no ambiente de homologação. + +### Bloqueios de segurança encontrados + +- O controller `api_sigerp` registra `req.params` e o corpo da requisição; + isso pode incluir senha, `sg_code` ou token. +- O JWT criado pelo código inclui a senha do usuário no payload, que não é + criptografado pelo formato JWT. +- Estado de autenticação e dados do usuário ficam em atributos mutáveis da + instância do controller; o isolamento entre requisições precisa ser + verificado. +- Nenhum contrato ou implementação Odoo 19 foi encontrado nesta inspeção. +- `coletor_android` também registra parâmetros com credenciais e monta uma + consulta de autenticação por interpolação de strings. O PDV não reutiliza + essas partes, não consulta `usuario.coletor` e não devolve hash de senha. + +Por esses motivos, o app não foi conectado diretamente ao controller `api_sigerp` +nem copiou o SQL de login do Coletor. O endpoint dedicado usa a sessão web Odoo. + +Antes de conectar dados reais, documentar para cada operação a URL/rota, +método, autenticação, headers, parâmetros, exemplos de request/response, +erros, timeout, permissões, idempotência e paginação. Os adaptadores Odoo 7 +e Odoo 19 devem implementar o contrato comum definido após essa confirmação. diff --git a/pdv/docs/DECISIONS.md b/pdv/docs/DECISIONS.md new file mode 100644 index 0000000..14c3d28 --- /dev/null +++ b/pdv/docs/DECISIONS.md @@ -0,0 +1,108 @@ +# Decisões e pendências + +## Implementado + +- O app mantém Flutter 3.16.5 e Dart 3.2.3; esses SDKs não foram atualizados. +- O `compileSdkVersion` Android foi definido como 34, exigido pelo plugin + `shared_preferences_android`; min/target SDK permanecem gerenciados pelo + Flutter. +- A navegação inicial usa rotas nomeadas do Flutter, sem biblioteca extra. +- As rotas de venda, carrinho, pagamento e histórico são protegidas e + exigem sessão. Nenhum login bem-sucedido é simulado. +- A URL e o identificador da empresa são persistidos com + `shared_preferences`; senhas não são persistidas e o cookie de sessão é + guardado via `flutter_secure_storage`. +- O formulário aceita até 14 caracteres alfanuméricos para o identificador. +- HTTPS é obrigatório fora do modo debug. HTTP é aceito apenas em debug para + permitir desenvolvimento em ambientes locais. +- Ao alterar servidor/empresa, a sessão local é invalidada. Cache de dados + ainda não existe. +- Login e teste de conexão usam contratos internos e adaptadores Odoo 7; a + homologação real ainda está pendente. +- A sessão em memória mantém o usuário e o `company_id` padrão retornados no + login, como contexto inicial para o catálogo. +- Foi selecionada uma API de negócio dedicada no módulo `pdv_pos`. O primeiro + endpoint definido é `GET /pdv_pos/health`, sem autenticação e sem dados + sensíveis; login e catálogo serão definidos separadamente. +- O botão Testar conexão usa o endpoint de health, exige HTTP 200 e o JSON + esperado, aplica timeout e não segue redirecionamentos. +- O login Odoo 7 combina seleção de database por CNPJ via `app_pdv_pos.config`, + validação da licença do dispositivo e autenticação de `res.users` em + `POST /pdv_pos/logar`. +- A sessão Odoo 7 usa o cookie HTTP `sid` e o `session_id` interno, ambos + armazenados com `flutter_secure_storage`; a senha não é persistida. +- Em execução desktop de desenvolvimento (por exemplo, Linux), o cookie de + sessão fica somente em memória para não depender do plugin nativo seguro. +- O tipo de licença `3` foi reservado ao PDV, sem reutilizar os tipos de + Coletor ou Comanda. +- O app pula a leitura/licença do dispositivo fora do Android para permitir + testes desktop; o login Odoo continua obrigatório. O valor de plataforma é + declarativo e não deve ser tratado como controle de segurança em produção. +- A permissão de câmera está declarada para uso futuro, mas não é solicitada + em tempo de execução nesta fase. + +## Fase 1 parcialmente concluída + +- Tela de login com usuário, senha (ocultável), validação, carregamento e + botão de saída, integrada à sessão web Odoo e checagem da licença do POS. +- Tela de configuração com carregamento, validação, salvar/cancelar e teste + de conexão com health check dedicado. +- Persistência local das configurações não sensíveis. +- A permissão de câmera está declarada para uso futuro, mas não é solicitada + em tempo de execução nesta fase. + +## Fase 2 iniciada + +- Departamentos carregam todos os registros, ordenados alfabeticamente; a UI + exibe apenas o nome e mantém o ID para consultar produtos. +- Produtos são carregados por departamento pelo método existente de Vendas + Externas, usando a empresa padrão do usuário e todas as páginas/registros. +- Não há paginação por decisão inicial; medir o catálogo POS real e rever caso + o carregamento seja pesado. +- A visualização Kanban usa três produtos por linha. A preferência Lista/Kanban + é persistida localmente por ID do usuário Odoo. + +## Fase 3 parcialmente concluída + +- Carrinho compartilhado entre Venda e Carrinho durante a sessão do app. +- Quantidade pode ser aumentada; o botão Menos não reduz abaixo de 1. A lixeira + remove explicitamente o item e Limpar carrinho exige confirmação. +- Total é uma prévia calculada em unidades mínimas inteiras; se algum preço + estiver indisponível, o total também é indicado como indisponível. + +## Fase 4 parcialmente concluída + +- Consulta de clientes por nome ou documento usa `financeiro.cliente`, filtra + pela empresa padrão e só retorna documento mascarado. +- Opções dinâmicas vêm de combinações ativas em `adm.condicao.forma`. +- A tela agrupa as formas em Dinheiro, PIX, Cartão de Crédito e Cartão de + Débito conforme os códigos Odoo; combinações múltiplas do mesmo grupo pedem + escolha da condição. +- É possível lançar várias parcelas e distribuir o valor da venda entre formas + diferentes, sem exceder o total. Dinheiro fica registrado como recebido; + PIX/cartões ficam pendentes de confirmação pela API do POS. +- Finalização NFC-e aceita, por enquanto, somente pagamentos totalmente em + dinheiro. O endpoint cria/valida o pedido e aguarda + `pedcap_button_faturar_pedido_nfce`; se a nota estiver vinculada, retorna + número/série/estado mesmo quando a autorização falhar. A tela bloqueia ações + durante a espera e exibe o erro; sem nota, libera uma nova tentativa. +- Cliente continua opcional. Se a configuração do Odoo exigir CPF/CNPJ para + NFC-e, o app pergunta antes de repetir a finalização. +- A tela final exibe número/série da nota e permite iniciar outra venda. O + botão de impressão aguarda o contrato da API/SDK da impressora do POS. + +## Pendências + +- Homologar `GET /pdv_pos/health` no servidor Odoo 7 alvo. +- Homologar login, cookie de sessão e tipo de licença `3` no serviço central. +- Validar se `DeviceInfo.id` é uma identidade estável/exclusiva nos POS alvo. +- Reavaliar paginação e cache persistente após medir o catálogo nos POS alvo. +- Definir versão/descoberta do Odoo e o uso do identificador enviado pelo app. +- Significado do identificador exibido como CNPJ. +- Modelo POS, versão mínima do Android e orientação alvo. +- Contrato da API oficial do POS para confirmar PIX/cartão e imprimir NFC-e, + inclusive reimpressão a partir do histórico de vendas. +- Exibir no histórico o número e a série da NFC-e vinculada a cada pedido. +- Homologar leitura por câmera e os demais requisitos de documento fiscal/ + impressora no modelo de POS escolhido. +- Regras para operação sem conexão. diff --git a/pdv/ios/.gitignore b/pdv/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/pdv/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/pdv/ios/Flutter/AppFrameworkInfo.plist b/pdv/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..9625e10 --- /dev/null +++ b/pdv/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 11.0 + + diff --git a/pdv/ios/Flutter/Debug.xcconfig b/pdv/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/pdv/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/pdv/ios/Flutter/Release.xcconfig b/pdv/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/pdv/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/pdv/ios/Runner.xcodeproj/project.pbxproj b/pdv/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..e7db173 --- /dev/null +++ b/pdv/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,614 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807E294A63A400263BE5 /* Frameworks */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1430; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.pdv; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = AE0B7B92F70575B8D7E0D07E /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.pdv.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 89B67EB44CE7B6631473024E /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.pdv.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 640959BDD8F10B91D80A66BE /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.pdv.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.pdv; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.pdv; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/pdv/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/pdv/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/pdv/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/pdv/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/pdv/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/pdv/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/pdv/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/pdv/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/pdv/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/pdv/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/pdv/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..87131a0 --- /dev/null +++ b/pdv/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pdv/ios/Runner.xcworkspace/contents.xcworkspacedata b/pdv/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/pdv/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/pdv/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/pdv/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/pdv/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/pdv/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/pdv/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/pdv/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/pdv/ios/Runner/AppDelegate.swift b/pdv/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..70693e4 --- /dev/null +++ b/pdv/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import UIKit +import Flutter + +@UIApplicationMain +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..f124868 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..e4b33c5 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..4c11cb2 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..e979654 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4bc2d56 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..7899731 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..2a26eb2 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..4c11cb2 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..efcd151 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..be8e633 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..be8e633 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..94e17f4 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..a18f4a4 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8c0edff Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..61700b7 Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/pdv/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/pdv/ios/Runner/Base.lproj/LaunchScreen.storyboard b/pdv/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/pdv/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pdv/ios/Runner/Base.lproj/Main.storyboard b/pdv/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/pdv/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pdv/ios/Runner/Info.plist b/pdv/ios/Runner/Info.plist new file mode 100644 index 0000000..a88cb59 --- /dev/null +++ b/pdv/ios/Runner/Info.plist @@ -0,0 +1,56 @@ + + + + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Pdv + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + pdv + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + NSCameraUsageDescription + A câmera é usada para ler códigos de barras dos produtos. + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/pdv/ios/Runner/Runner-Bridging-Header.h b/pdv/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/pdv/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/pdv/ios/RunnerTests/RunnerTests.swift b/pdv/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/pdv/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pdv/lib/app/app.dart b/pdv/lib/app/app.dart new file mode 100644 index 0000000..6ee4f45 --- /dev/null +++ b/pdv/lib/app/app.dart @@ -0,0 +1,27 @@ +import 'package:flutter/material.dart'; + +import 'app_services.dart'; +import 'router/app_router.dart'; +import 'theme/app_theme.dart'; + +class PdvApp extends StatelessWidget { + const PdvApp({this.services, super.key}); + + static final GlobalKey navigatorKey = + GlobalKey(); + + final AppServices? services; + + @override + Widget build(BuildContext context) { + final appServices = services ?? AppServices.defaults; + return MaterialApp( + title: 'PDV', + debugShowCheckedModeBanner: false, + theme: AppTheme.light, + navigatorKey: navigatorKey, + initialRoute: AppRoutes.login, + onGenerateRoute: AppRouter(services: appServices).onGenerateRoute, + ); + } +} diff --git a/pdv/lib/app/app_services.dart b/pdv/lib/app/app_services.dart new file mode 100644 index 0000000..44bd052 --- /dev/null +++ b/pdv/lib/app/app_services.dart @@ -0,0 +1,82 @@ +import '../core/config/app_version_provider.dart'; +import '../core/config/pos_device_provider.dart'; +import '../core/storage/session_storage_factory.dart'; +import '../data/datasources/remote/odoo_connection_tester.dart'; +import '../data/datasources/remote/odoo_session_api_client.dart'; +import '../data/repositories/odoo_customer_repository.dart'; +import '../data/repositories/odoo_payment_methods_repository.dart'; +import '../data/repositories/odoo_sale_checkout_repository.dart'; +import '../data/repositories/odoo_sales_history_repository.dart'; +import '../data/repositories/odoo_catalog_repository.dart'; +import '../data/repositories/odoo_auth_repository.dart'; +import '../data/repositories/shared_preferences_sale_view_preference_repository.dart'; +import '../data/repositories/shared_preferences_settings_repository.dart'; +import '../domain/repositories/auth_repository.dart'; +import '../domain/repositories/cart_repository.dart'; +import '../domain/repositories/catalog_repository.dart'; +import '../domain/repositories/customer_repository.dart'; +import '../domain/repositories/connection_tester.dart'; +import '../domain/repositories/payment_methods_repository.dart'; +import '../domain/repositories/sale_checkout_repository.dart'; +import '../domain/repositories/sales_history_repository.dart'; +import '../domain/repositories/settings_repository.dart'; +import '../domain/repositories/sale_view_preference_repository.dart'; + +class AppServices { + const AppServices({ + required this.settingsRepository, + required this.connectionTester, + required this.authRepository, + required this.appVersionProvider, + required this.posDeviceProvider, + required this.catalogRepository, + required this.cartRepository, + required this.saleViewPreferenceRepository, + required this.customerRepository, + required this.paymentMethodsRepository, + required this.saleCheckoutRepository, + required this.salesHistoryRepository, + }); + + static final defaults = _createDefaults(); + + static AppServices _createDefaults() { + const settingsRepository = SharedPreferencesSettingsRepository(); + final sessionStorage = createSessionStorage(); + final authRepository = OdooAuthRepository(sessionStorage: sessionStorage); + final apiClient = OdooSessionApiClient( + authRepository: authRepository, + settingsRepository: settingsRepository, + sessionStorage: sessionStorage, + ); + return AppServices( + settingsRepository: settingsRepository, + connectionTester: OdooConnectionTester(), + authRepository: authRepository, + appVersionProvider: const PackageInfoAppVersionProvider(), + posDeviceProvider: PlatformPosDeviceProvider(), + catalogRepository: OdooCatalogRepository(apiClient: apiClient), + customerRepository: OdooCustomerRepository(apiClient: apiClient), + paymentMethodsRepository: + OdooPaymentMethodsRepository(apiClient: apiClient), + saleCheckoutRepository: OdooSaleCheckoutRepository(apiClient: apiClient), + salesHistoryRepository: OdooSalesHistoryRepository(apiClient: apiClient), + cartRepository: InMemoryCartRepository(), + saleViewPreferenceRepository: + const SharedPreferencesSaleViewPreferenceRepository(), + ); + } + + final SettingsRepository settingsRepository; + final ConnectionTester connectionTester; + final AuthRepository authRepository; + final AppVersionProvider appVersionProvider; + final PosDeviceProvider posDeviceProvider; + final CatalogRepository catalogRepository; + final CartRepository cartRepository; + final SaleViewPreferenceRepository saleViewPreferenceRepository; + final CustomerRepository customerRepository; + final PaymentMethodsRepository paymentMethodsRepository; + final SaleCheckoutRepository saleCheckoutRepository; + final SalesHistoryRepository salesHistoryRepository; +} diff --git a/pdv/lib/app/router/app_router.dart b/pdv/lib/app/router/app_router.dart new file mode 100644 index 0000000..f1e0caa --- /dev/null +++ b/pdv/lib/app/router/app_router.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; + +import '../app_services.dart'; +import '../../domain/entities/customer.dart'; +import '../../domain/entities/sale_completion.dart'; +import '../../features/cart/presentation/cart_screen.dart'; +import '../../features/customer_search/presentation/customer_search_screen.dart'; +import '../../features/login/presentation/login_screen.dart'; +import '../../features/menu/presentation/menu_screen.dart'; +import '../../features/payment/presentation/payment_screen.dart'; +import '../../features/payment/presentation/sale_complete_screen.dart'; +import '../../features/sale/presentation/sale_screen.dart'; +import '../../features/sales_history/presentation/sales_history_screen.dart'; +import '../../features/settings/presentation/settings_screen.dart'; +import '../../features/shared/presentation/placeholder_screen.dart'; + +class AppRoutes { + AppRoutes._(); + + static const login = '/login'; + static const menu = '/menu'; + static const settings = '/settings'; + static const sale = '/sale'; + static const cart = '/cart'; + static const payment = '/payment'; + static const customerSearch = '/customer-search'; + static const saleComplete = '/sale-complete'; + static const salesHistory = '/sales-history'; + static const saleDetail = '/sale-detail'; +} + +class AppRouter { + AppRouter({required this.services}); + + final AppServices services; + + static const _protectedRoutes = { + AppRoutes.sale, + AppRoutes.menu, + AppRoutes.cart, + AppRoutes.payment, + AppRoutes.customerSearch, + AppRoutes.saleComplete, + AppRoutes.salesHistory, + AppRoutes.saleDetail, + }; + + Route onGenerateRoute(RouteSettings settings) { + final routeName = settings.name ?? AppRoutes.login; + if (_protectedRoutes.contains(routeName) && + !services.authRepository.isAuthenticated) { + if (routeName == AppRoutes.customerSearch) { + return MaterialPageRoute( + settings: const RouteSettings(name: AppRoutes.login), + builder: (_) => LoginScreen(services: services), + ); + } + return MaterialPageRoute( + settings: const RouteSettings(name: AppRoutes.login), + builder: (_) => LoginScreen(services: services), + ); + } + + if (routeName == AppRoutes.customerSearch) { + return MaterialPageRoute( + settings: settings, + builder: (_) => CustomerSearchScreen(services: services), + ); + } + + if (routeName == AppRoutes.saleComplete) { + final completion = settings.arguments; + if (completion is SaleCompletion) { + return MaterialPageRoute( + settings: settings, + builder: (_) => SaleCompleteScreen( + services: services, + completion: completion, + ), + ); + } + } + + final page = switch (routeName) { + AppRoutes.login => LoginScreen(services: services), + AppRoutes.menu => MenuScreen(services: services), + AppRoutes.settings => SettingsScreen(services: services), + AppRoutes.sale => SaleScreen(services: services), + AppRoutes.cart => CartScreen(services: services), + AppRoutes.payment => PaymentScreen(services: services), + AppRoutes.saleComplete => const PlaceholderScreen( + title: 'Encerramento da venda', + message: 'Dados da NFC-e não recebidos.', + ), + AppRoutes.salesHistory => SalesHistoryScreen(services: services), + AppRoutes.saleDetail => const PlaceholderScreen( + title: 'Detalhes da venda', + message: 'Os detalhes serão carregados do servidor.', + ), + _ => const PlaceholderScreen( + title: 'Página não encontrada', + message: 'O endereço solicitado não existe.', + ), + }; + + return MaterialPageRoute( + settings: settings, + builder: (_) => page, + ); + } +} diff --git a/pdv/lib/app/theme/app_theme.dart b/pdv/lib/app/theme/app_theme.dart new file mode 100644 index 0000000..a0b1276 --- /dev/null +++ b/pdv/lib/app/theme/app_theme.dart @@ -0,0 +1,50 @@ +import 'package:flutter/material.dart'; + +class AppTheme { + AppTheme._(); + + static const _brandColor = Color(0xFF087F76); + + static ThemeData get light { + final colorScheme = ColorScheme.fromSeed( + seedColor: _brandColor, + brightness: Brightness.light, + ); + + return ThemeData( + useMaterial3: true, + colorScheme: colorScheme, + scaffoldBackgroundColor: const Color(0xFFF6F8F9), + appBarTheme: const AppBarTheme( + centerTitle: false, + backgroundColor: Color(0xFFF6F8F9), + surfaceTintColor: Colors.transparent, + ), + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: Colors.white, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: Color(0xFFD7DEDF)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: Color(0xFFD7DEDF)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _brandColor, width: 2), + ), + ), + filledButtonTheme: FilledButtonThemeData( + style: FilledButton.styleFrom( + minimumSize: const Size.fromHeight(52), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + textStyle: const TextStyle(fontWeight: FontWeight.w600), + ), + ), + ); + } +} diff --git a/pdv/lib/core/config/app_version_provider.dart b/pdv/lib/core/config/app_version_provider.dart new file mode 100644 index 0000000..d0529bc --- /dev/null +++ b/pdv/lib/core/config/app_version_provider.dart @@ -0,0 +1,15 @@ +import 'package:package_info_plus/package_info_plus.dart'; + +abstract interface class AppVersionProvider { + Future getVersion(); +} + +class PackageInfoAppVersionProvider implements AppVersionProvider { + const PackageInfoAppVersionProvider(); + + @override + Future getVersion() async { + final packageInfo = await PackageInfo.fromPlatform(); + return packageInfo.version; + } +} diff --git a/pdv/lib/core/config/pos_device_provider.dart b/pdv/lib/core/config/pos_device_provider.dart new file mode 100644 index 0000000..b573e1a --- /dev/null +++ b/pdv/lib/core/config/pos_device_provider.dart @@ -0,0 +1,30 @@ +import 'dart:io'; + +import 'package:device_info_plus/device_info_plus.dart'; + +import '../../domain/entities/pos_device.dart'; + +abstract interface class PosDeviceProvider { + Future getDevice(); +} + +class PlatformPosDeviceProvider implements PosDeviceProvider { + PlatformPosDeviceProvider({DeviceInfoPlugin? plugin}) + : _plugin = plugin ?? DeviceInfoPlugin(); + + final DeviceInfoPlugin _plugin; + + @override + Future getDevice() async { + if (!Platform.isAndroid) { + return PosDevice(platform: Platform.operatingSystem); + } + final info = await _plugin.androidInfo; + return PosDevice( + platform: 'android', + serial: info.id, + model: info.model, + brand: info.brand, + ); + } +} diff --git a/pdv/lib/core/config/server_url_validator.dart b/pdv/lib/core/config/server_url_validator.dart new file mode 100644 index 0000000..e8231d3 --- /dev/null +++ b/pdv/lib/core/config/server_url_validator.dart @@ -0,0 +1,25 @@ +class ServerUrlValidator { + ServerUrlValidator._(); + + static String? validate(String value, {bool requireHttps = false}) { + final trimmed = value.trim(); + if (trimmed.isEmpty) { + return 'Informe a URL do servidor.'; + } + + final uri = Uri.tryParse(trimmed); + if (uri == null || !uri.hasAuthority || uri.host.isEmpty) { + return 'Informe uma URL válida, incluindo o host.'; + } + if (uri.scheme != 'https' && uri.scheme != 'http') { + return 'A URL deve usar HTTP ou HTTPS.'; + } + if (requireHttps && uri.scheme != 'https') { + return 'Use uma URL HTTPS para proteger a conexão.'; + } + if (uri.userInfo.isNotEmpty || uri.hasFragment) { + return 'A URL não pode conter credenciais ou fragmentos.'; + } + return null; + } +} diff --git a/pdv/lib/core/storage/secure_session_storage.dart b/pdv/lib/core/storage/secure_session_storage.dart new file mode 100644 index 0000000..05b4bba --- /dev/null +++ b/pdv/lib/core/storage/secure_session_storage.dart @@ -0,0 +1,85 @@ +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +abstract interface class SecureSessionStorage { + Future readCookie(); + + Future readServerUrl(); + + Future readSessionId(); + + Future writeSession( + {required String cookie, + required String serverUrl, + required String sessionId}); + + Future clearCookie(); +} + +class FlutterSecureSessionStorage implements SecureSessionStorage { + FlutterSecureSessionStorage({FlutterSecureStorage? storage}) + : _storage = storage ?? const FlutterSecureStorage(); + + static const _cookieKey = 'pdv.odoo_session_cookie'; + static const _serverUrlKey = 'pdv.odoo_session_server_url'; + static const _sessionIdKey = 'pdv.odoo_session_id'; + final FlutterSecureStorage _storage; + + @override + Future readCookie() => _storage.read(key: _cookieKey); + + @override + Future readServerUrl() => _storage.read(key: _serverUrlKey); + + @override + Future readSessionId() => _storage.read(key: _sessionIdKey); + + @override + Future writeSession( + {required String cookie, + required String serverUrl, + required String sessionId}) async { + await _storage.write(key: _cookieKey, value: cookie); + await _storage.write(key: _serverUrlKey, value: serverUrl); + await _storage.write(key: _sessionIdKey, value: sessionId); + } + + @override + Future clearCookie() async { + await _storage.delete(key: _cookieKey); + await _storage.delete(key: _serverUrlKey); + await _storage.delete(key: _sessionIdKey); + } +} + +class InMemorySessionStorage implements SecureSessionStorage { + String? _cookie; + String? _serverUrl; + String? _sessionId; + + @override + Future readCookie() async => _cookie; + + @override + Future readServerUrl() async => _serverUrl; + + @override + Future readSessionId() async => _sessionId; + + @override + Future writeSession({ + required String cookie, + required String serverUrl, + required String sessionId, + }) async { + _cookie = cookie; + _serverUrl = serverUrl; + _sessionId = sessionId; + } + + @override + Future clearCookie() async { + _cookie = null; + _serverUrl = null; + _sessionId = null; + } +} diff --git a/pdv/lib/core/storage/session_storage_factory.dart b/pdv/lib/core/storage/session_storage_factory.dart new file mode 100644 index 0000000..eeae2d5 --- /dev/null +++ b/pdv/lib/core/storage/session_storage_factory.dart @@ -0,0 +1,17 @@ +import 'dart:io'; + +import 'package:flutter/foundation.dart'; + +import 'secure_session_storage.dart'; + +SecureSessionStorage createSessionStorage() { + if (Platform.isAndroid || Platform.isIOS) { + return FlutterSecureSessionStorage(); + } + if (kDebugMode) { + return InMemorySessionStorage(); + } + throw UnsupportedError( + 'O armazenamento seguro de sessão só está disponível em Android/iOS.', + ); +} diff --git a/pdv/lib/core/utils/currency_formatter.dart b/pdv/lib/core/utils/currency_formatter.dart new file mode 100644 index 0000000..15a5e09 --- /dev/null +++ b/pdv/lib/core/utils/currency_formatter.dart @@ -0,0 +1,24 @@ +class CurrencyFormatter { + CurrencyFormatter._(); + + static String formatBrl(int? minorUnits) { + if (minorUnits == null) return 'Preço indisponível'; + + final negative = minorUnits < 0; + final value = minorUnits.abs(); + final whole = value ~/ 100; + final cents = (value % 100).toString().padLeft(2, '0'); + final groupedWhole = _groupThousands(whole.toString()); + final sign = negative ? '-' : ''; + return '${sign}R\$ $groupedWhole,$cents'; + } + + static String _groupThousands(String digits) { + final groups = []; + for (var end = digits.length; end > 0; end -= 3) { + final start = end - 3 < 0 ? 0 : end - 3; + groups.insert(0, digits.substring(start, end)); + } + return groups.join('.'); + } +} diff --git a/pdv/lib/core/widgets/app_button.dart b/pdv/lib/core/widgets/app_button.dart new file mode 100644 index 0000000..83e736d --- /dev/null +++ b/pdv/lib/core/widgets/app_button.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; + +class AppButton extends StatelessWidget { + const AppButton({ + required this.label, + required this.onPressed, + this.icon, + super.key, + }); + + final String label; + final VoidCallback? onPressed; + final IconData? icon; + + @override + Widget build(BuildContext context) { + return FilledButton.icon( + onPressed: onPressed, + icon: Icon(icon ?? Icons.arrow_forward), + label: Text(label), + ); + } +} diff --git a/pdv/lib/core/widgets/app_text_field.dart b/pdv/lib/core/widgets/app_text_field.dart new file mode 100644 index 0000000..2a589ee --- /dev/null +++ b/pdv/lib/core/widgets/app_text_field.dart @@ -0,0 +1,34 @@ +import 'package:flutter/material.dart'; + +class AppTextField extends StatelessWidget { + const AppTextField({ + required this.label, + this.controller, + this.obscureText = false, + this.keyboardType, + this.textInputAction, + this.prefixIcon, + super.key, + }); + + final String label; + final TextEditingController? controller; + final bool obscureText; + final TextInputType? keyboardType; + final TextInputAction? textInputAction; + final IconData? prefixIcon; + + @override + Widget build(BuildContext context) { + return TextField( + controller: controller, + obscureText: obscureText, + keyboardType: keyboardType, + textInputAction: textInputAction, + decoration: InputDecoration( + labelText: label, + prefixIcon: prefixIcon == null ? null : Icon(prefixIcon), + ), + ); + } +} diff --git a/pdv/lib/core/widgets/empty_view.dart b/pdv/lib/core/widgets/empty_view.dart new file mode 100644 index 0000000..dc9867c --- /dev/null +++ b/pdv/lib/core/widgets/empty_view.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; + +class EmptyView extends StatelessWidget { + const EmptyView({ + required this.title, + required this.message, + this.icon = Icons.inbox_outlined, + super.key, + }); + + final String title; + final String message; + final IconData icon; + + @override + Widget build(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 48, color: Theme.of(context).colorScheme.outline), + const SizedBox(height: 12), + Text(title, style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 4), + Text(message, textAlign: TextAlign.center), + ], + ), + ), + ); + } +} diff --git a/pdv/lib/core/widgets/error_view.dart b/pdv/lib/core/widgets/error_view.dart new file mode 100644 index 0000000..9ba4ed8 --- /dev/null +++ b/pdv/lib/core/widgets/error_view.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; + +class ErrorView extends StatelessWidget { + const ErrorView({ + required this.message, + this.onRetry, + super.key, + }); + + final String message; + final VoidCallback? onRetry; + + @override + Widget build(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.cloud_off_outlined, + size: 40, + color: Theme.of(context).colorScheme.error, + ), + const SizedBox(height: 12), + Text(message, textAlign: TextAlign.center), + if (onRetry != null) ...[ + const SizedBox(height: 16), + TextButton.icon( + onPressed: onRetry, + icon: const Icon(Icons.refresh), + label: const Text('Tentar novamente'), + ), + ], + ], + ), + ), + ); + } +} diff --git a/pdv/lib/core/widgets/loading_view.dart b/pdv/lib/core/widgets/loading_view.dart new file mode 100644 index 0000000..8acaf54 --- /dev/null +++ b/pdv/lib/core/widgets/loading_view.dart @@ -0,0 +1,21 @@ +import 'package:flutter/material.dart'; + +class LoadingView extends StatelessWidget { + const LoadingView({this.message = 'Carregando...', super.key}); + + final String message; + + @override + Widget build(BuildContext context) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const CircularProgressIndicator(), + const SizedBox(height: 16), + Text(message), + ], + ), + ); + } +} diff --git a/pdv/lib/data/datasources/remote/odoo_api_uri_builder.dart b/pdv/lib/data/datasources/remote/odoo_api_uri_builder.dart new file mode 100644 index 0000000..ce0b693 --- /dev/null +++ b/pdv/lib/data/datasources/remote/odoo_api_uri_builder.dart @@ -0,0 +1,15 @@ +class OdooApiUriBuilder { + OdooApiUriBuilder._(); + + static Uri endpoint(Uri serverUri, String endpointPath) { + final basePath = serverUri.path.replaceFirst(RegExp(r'/+$'), ''); + final normalizedEndpoint = + endpointPath.startsWith('/') ? endpointPath : '/$endpointPath'; + return Uri( + scheme: serverUri.scheme, + host: serverUri.host, + port: serverUri.hasPort ? serverUri.port : null, + path: '$basePath$normalizedEndpoint', + ); + } +} diff --git a/pdv/lib/data/datasources/remote/odoo_connection_tester.dart b/pdv/lib/data/datasources/remote/odoo_connection_tester.dart new file mode 100644 index 0000000..5897d15 --- /dev/null +++ b/pdv/lib/data/datasources/remote/odoo_connection_tester.dart @@ -0,0 +1,71 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart' as http; + +import '../../../domain/repositories/connection_tester.dart'; +import 'odoo_api_uri_builder.dart'; + +class OdooConnectionTester implements ConnectionTester { + OdooConnectionTester({http.Client? client}) + : _client = client ?? http.Client(); + + static const _timeout = Duration(seconds: 10); + final http.Client _client; + + @override + Future test(Uri serverUri) async { + final healthUri = OdooApiUriBuilder.endpoint(serverUri, '/pdv_pos/health'); + try { + final request = http.Request('GET', healthUri) + ..followRedirects = false + ..headers['Accept'] = 'application/json'; + final response = await _client + .send(request) + .then(http.Response.fromStream) + .timeout(_timeout); + if (response.statusCode != HttpStatus.ok) { + return ConnectionTestResult( + isAvailable: false, + message: 'O servidor respondeu com erro HTTP ${response.statusCode}.', + ); + } + + final body = jsonDecode(response.body); + if (body is Map && + body['status'] == 'ok' && + body['api_version'] == 1) { + return const ConnectionTestResult( + isAvailable: true, + message: 'Conexão com o servidor estabelecida.', + ); + } + + return const ConnectionTestResult( + isAvailable: false, + message: 'O servidor não confirmou a disponibilidade da API PDV.', + ); + } on TimeoutException { + return const ConnectionTestResult( + isAvailable: false, + message: 'Tempo esgotado ao conectar ao servidor.', + ); + } on SocketException { + return const ConnectionTestResult( + isAvailable: false, + message: 'Não foi possível alcançar o servidor.', + ); + } on FormatException { + return const ConnectionTestResult( + isAvailable: false, + message: 'O servidor retornou uma resposta inválida.', + ); + } catch (_) { + return const ConnectionTestResult( + isAvailable: false, + message: 'Não foi possível testar a conexão com o servidor.', + ); + } + } +} diff --git a/pdv/lib/data/datasources/remote/odoo_session_api_client.dart b/pdv/lib/data/datasources/remote/odoo_session_api_client.dart new file mode 100644 index 0000000..91cd048 --- /dev/null +++ b/pdv/lib/data/datasources/remote/odoo_session_api_client.dart @@ -0,0 +1,156 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart' as http; + +import '../../../core/storage/secure_session_storage.dart'; +import '../../../domain/repositories/auth_repository.dart'; +import '../../../domain/repositories/settings_repository.dart'; +import 'odoo_api_uri_builder.dart'; + +class OdooSessionApiClient { + OdooSessionApiClient({ + required AuthRepository authRepository, + required SettingsRepository settingsRepository, + required SecureSessionStorage sessionStorage, + http.Client? client, + }) : _authRepository = authRepository, + _settingsRepository = settingsRepository, + _sessionStorage = sessionStorage, + _client = client ?? http.Client(); + + static const _timeout = Duration(seconds: 60); + final AuthRepository _authRepository; + final SettingsRepository _settingsRepository; + final SecureSessionStorage _sessionStorage; + final http.Client _client; + + Future> getJson( + String endpoint, { + Map query = const {}, + }) => + _request('GET', endpoint, query: query); + + Future> postForm( + String endpoint, { + required Map body, + Duration? timeout, + }) => + _request('POST', endpoint, body: body, requestTimeout: timeout); + + Future> _request( + String method, + String endpoint, { + Map query = const {}, + Map body = const {}, + Duration? requestTimeout, + }) async { + if (!_authRepository.isAuthenticated || + _authRepository.currentSession == null) { + throw const OdooApiException( + 'session_required', + 'A sessão expirou. Entre novamente.', + ); + } + + final settings = await _settingsRepository.load(); + if (settings?.isConfigured != true) { + throw const OdooApiException( + 'configuration_required', + 'Configure o servidor antes de continuar.', + ); + } + + final cookie = await _sessionStorage.readCookie(); + final sessionId = await _sessionStorage.readSessionId(); + if (cookie == null || sessionId == null) { + throw const OdooApiException( + 'session_required', + 'A sessão do servidor não está disponível. Entre novamente.', + ); + } + + final endpointUri = OdooApiUriBuilder.endpoint( + Uri.parse(settings!.serverUrl), + endpoint, + ); + final uri = method == 'GET' + ? endpointUri.replace( + queryParameters: {'session_id': sessionId, ...query}, + ) + : endpointUri; + final request = http.Request(method, uri) + ..followRedirects = false + ..headers['Accept'] = 'application/json' + ..headers['Cookie'] = cookie; + if (method == 'POST') { + request + ..headers['Content-Type'] = + 'application/x-www-form-urlencoded; charset=utf-8' + ..body = Uri(queryParameters: {'session_id': sessionId, ...body}).query; + } + + try { + final response = await _client + .send(request) + .then(http.Response.fromStream) + .timeout(requestTimeout ?? _timeout); + if (response.statusCode != HttpStatus.ok) { + throw OdooApiException( + 'http_error', + 'O servidor respondeu com erro HTTP ${response.statusCode}.', + ); + } + + final decoded = jsonDecode(response.body); + if (decoded is! Map) { + throw const OdooApiException( + 'invalid_response', + 'O servidor retornou uma resposta inválida.', + ); + } + if (decoded['status'] != 'ok') { + final code = decoded['code']; + final message = decoded['message']; + throw OdooApiException( + code is String ? code : 'api_error', + message is String ? message : 'O servidor não concluiu a operação.', + ); + } + return decoded; + } on TimeoutException { + throw const OdooApiException( + 'timeout', + 'Tempo esgotado ao consultar o servidor.', + ); + } on SocketException { + throw const OdooApiException( + 'network_error', + 'Não foi possível alcançar o servidor.', + ); + } on OdooApiException { + rethrow; + } on FormatException { + throw const OdooApiException( + 'invalid_response', + 'O servidor retornou dados inválidos.', + ); + } catch (_) { + throw const OdooApiException( + 'network_error', + 'Falha de comunicação com o servidor.', + ); + } + } +} + +class OdooApiException implements Exception { + const OdooApiException(this.code, this.message); + + final String code; + final String message; + + @override + String toString() => message; +} diff --git a/pdv/lib/data/repositories/odoo_auth_repository.dart b/pdv/lib/data/repositories/odoo_auth_repository.dart new file mode 100644 index 0000000..96b174a --- /dev/null +++ b/pdv/lib/data/repositories/odoo_auth_repository.dart @@ -0,0 +1,207 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:developer' as developer; +import 'dart:io'; + +import 'package:http/http.dart' as http; + +import '../../core/storage/secure_session_storage.dart'; +import '../../domain/entities/app_settings.dart'; +import '../../domain/entities/app_session.dart'; +import '../../domain/entities/pos_device.dart'; +import '../../domain/repositories/auth_repository.dart'; +import '../datasources/remote/odoo_api_uri_builder.dart'; + +class OdooAuthRepository implements AuthRepository { + OdooAuthRepository({ + required SecureSessionStorage sessionStorage, + http.Client? client, + }) : _sessionStorage = sessionStorage, + _client = client ?? http.Client(); + + static const _requestTimeout = Duration(seconds: 60); + final SecureSessionStorage _sessionStorage; + final http.Client _client; + Uri? _activeServerUri; + bool _isAuthenticated = false; + AppSession? _currentSession; + + @override + bool get isAuthenticated => _isAuthenticated; + + @override + AppSession? get currentSession => _currentSession; + + @override + Future authenticate({ + required String username, + required String password, + required AppSettings settings, + required PosDevice device, + required String appVersion, + }) async { + if (await _sessionStorage.readCookie() != null) { + await logout(); + } + _isAuthenticated = false; + _currentSession = null; + final serverUri = Uri.parse(settings.serverUrl); + final endpoint = OdooApiUriBuilder.endpoint(serverUri, '/pdv_pos/logar'); + final response = await _sendPost( + endpoint, + body: { + 'cnpj': settings.companyIdentifier, + 'username': username, + 'password': password, + 'platform': device.platform, + if (device.serial != null) 'serial': device.serial!, + if (device.model != null) 'model': device.model!, + if (device.brand != null) 'brand': device.brand!, + 'version': appVersion, + }, + ); + + final payload = _decodeResponse(response); + if (payload['status'] != 'ok') { + final message = payload['message']; + throw AuthUnavailableException( + message is String + ? message + : 'Não foi possível autenticar no servidor.', + ); + } + + final cookie = _sessionCookie(response.headers['set-cookie']); + final sessionId = payload['session_id']; + if (cookie == null || sessionId is! String || sessionId.isEmpty) { + throw const AuthUnavailableException( + 'O servidor não iniciou uma sessão segura para o PDV.', + ); + } + + await _sessionStorage.writeSession( + cookie: cookie, + serverUrl: settings.serverUrl, + sessionId: sessionId, + ); + final user = payload['user']; + final userId = user is Map ? user['id'] : null; + if (userId is! num) { + await _sessionStorage.clearCookie(); + throw const AuthUnavailableException( + 'O servidor não retornou os dados do operador.', + ); + } + final companyIdValue = payload['company_id']; + final companyNameValue = payload['company_name']; + _currentSession = AppSession( + userId: userId.toInt(), + userName: user['name'] is String ? user['name'] as String : username, + companyId: companyIdValue is num ? companyIdValue.toInt() : null, + companyName: companyNameValue is String ? companyNameValue : null, + ); + _activeServerUri = serverUri; + _isAuthenticated = true; + return _currentSession!; + } + + @override + Future logout() async { + var serverUri = _activeServerUri; + final cookie = await _sessionStorage.readCookie(); + final sessionId = await _sessionStorage.readSessionId(); + if (serverUri == null) { + final storedServerUrl = await _sessionStorage.readServerUrl(); + if (storedServerUrl != null) serverUri = Uri.tryParse(storedServerUrl); + } + try { + if (serverUri != null && cookie != null && sessionId != null) { + await _sendPost( + OdooApiUriBuilder.endpoint(serverUri, '/pdv_pos/logout'), + body: {'session_id': sessionId}, + cookie: cookie, + ); + } + } catch (_) { + // Local credentials are cleared even if the server cannot be reached. + } finally { + await _sessionStorage.clearCookie(); + _activeServerUri = null; + _isAuthenticated = false; + _currentSession = null; + } + } + + Future _sendPost( + Uri uri, { + required Map body, + String? cookie, + }) async { + final request = http.Request('POST', uri) + ..followRedirects = false + ..headers['Accept'] = 'application/json' + ..headers['Content-Type'] = + 'application/x-www-form-urlencoded; charset=utf-8' + ..body = Uri(queryParameters: body).query; + if (cookie != null) request.headers['Cookie'] = cookie; + developer.log('Enviando chamada HTTP ${request.method} ${uri.path}.', + name: 'pdv.auth'); + + try { + final response = await _client + .send(request) + .then(http.Response.fromStream) + .timeout(_requestTimeout); + if (response.statusCode != HttpStatus.ok) { + developer.log( + 'Resposta HTTP ${response.statusCode} em ${uri.path}.', + name: 'pdv.auth', + ); + throw const AuthUnavailableException( + 'O servidor não conseguiu processar a solicitação do PDV.', + ); + } + return response; + } on TimeoutException { + developer.log('Timeout na chamada HTTP ${uri.path}.', name: 'pdv.auth'); + throw const AuthUnavailableException( + 'Tempo esgotado ao comunicar com o servidor.', + ); + } on SocketException { + developer.log('Falha de socket na chamada HTTP ${uri.path}.', + name: 'pdv.auth'); + throw const AuthUnavailableException( + 'Não foi possível alcançar o servidor.', + ); + } on AuthUnavailableException { + rethrow; + } catch (error, stackTrace) { + developer.log( + 'Falha HTTP ${uri.path}: ${error.runtimeType}.', + name: 'pdv.auth', + stackTrace: stackTrace, + ); + throw const AuthUnavailableException( + 'Falha de comunicação com o servidor.', + ); + } + } + + Map _decodeResponse(http.Response response) { + try { + final decoded = jsonDecode(response.body); + if (decoded is Map) return decoded; + } on FormatException { + // Mapped below to a safe protocol error. + } + throw const AuthUnavailableException( + 'O servidor retornou uma resposta inválida.', + ); + } + + String? _sessionCookie(String? setCookieHeader) { + if (setCookieHeader == null) return null; + final cookie = setCookieHeader.split(';').first.trim(); + return cookie.startsWith('sid=') && cookie.length > 4 ? cookie : null; + } +} diff --git a/pdv/lib/data/repositories/odoo_catalog_repository.dart b/pdv/lib/data/repositories/odoo_catalog_repository.dart new file mode 100644 index 0000000..b262787 --- /dev/null +++ b/pdv/lib/data/repositories/odoo_catalog_repository.dart @@ -0,0 +1,67 @@ +import '../../domain/entities/department.dart'; +import '../../domain/entities/product.dart'; +import '../../domain/repositories/catalog_repository.dart'; +import '../datasources/remote/odoo_session_api_client.dart'; + +class OdooCatalogRepository implements CatalogRepository { + const OdooCatalogRepository({required this.apiClient}); + + final OdooSessionApiClient apiClient; + + @override + Future> fetchDepartments() async { + try { + final payload = await apiClient.getJson('/pdv_pos/departamentos'); + final records = payload['departments']; + if (records is! List) { + throw const CatalogException('Resposta de departamentos inválida.'); + } + return records + .whereType>() + .map(Department.fromJson) + .toList(growable: false); + } on OdooApiException catch (error) { + throw CatalogException(error.message); + } + } + + @override + Future> fetchProductsByDepartment(int departmentId) async { + try { + final payload = await apiClient.getJson( + '/pdv_pos/produtos_por_departamento', + query: {'department_id': departmentId.toString()}, + ); + final records = payload['products']; + if (records is! List) { + throw const CatalogException('Resposta de produtos inválida.'); + } + return records + .whereType>() + .map(Product.fromJson) + .toList(growable: false); + } on OdooApiException catch (error) { + throw CatalogException(error.message); + } + } + + @override + Future fetchProductByBarcode(String barcode) async { + try { + final payload = await apiClient.getJson( + '/pdv_pos/produto_por_codigo_barra', + query: {'barcode': barcode}, + ); + final record = payload['product']; + if (record == null) return null; + if (record is! Map) { + throw const CatalogException('Resposta de produto inválida.'); + } + return Product.fromJson(record); + } on OdooApiException catch (error) { + throw CatalogException(error.message); + } on FormatException { + throw const CatalogException('O servidor retornou um produto inválido.'); + } + } +} diff --git a/pdv/lib/data/repositories/odoo_customer_repository.dart b/pdv/lib/data/repositories/odoo_customer_repository.dart new file mode 100644 index 0000000..22b8d83 --- /dev/null +++ b/pdv/lib/data/repositories/odoo_customer_repository.dart @@ -0,0 +1,29 @@ +import '../../domain/entities/customer.dart'; +import '../../domain/repositories/customer_repository.dart'; +import '../datasources/remote/odoo_session_api_client.dart'; + +class OdooCustomerRepository implements CustomerRepository { + const OdooCustomerRepository({required this.apiClient}); + + final OdooSessionApiClient apiClient; + + @override + Future> search(String query) async { + try { + final payload = await apiClient.postForm( + '/pdv_pos/clientes', + body: {'query': query.trim()}, + ); + final records = payload['customers']; + if (records is! List) { + throw const CustomerSearchException('Resposta de clientes inválida.'); + } + return records + .whereType>() + .map(Customer.fromJson) + .toList(growable: false); + } on OdooApiException catch (error) { + throw CustomerSearchException(error.message); + } + } +} diff --git a/pdv/lib/data/repositories/odoo_payment_methods_repository.dart b/pdv/lib/data/repositories/odoo_payment_methods_repository.dart new file mode 100644 index 0000000..713127a --- /dev/null +++ b/pdv/lib/data/repositories/odoo_payment_methods_repository.dart @@ -0,0 +1,28 @@ +import '../../domain/entities/payment_method.dart'; +import '../../domain/repositories/payment_methods_repository.dart'; +import '../datasources/remote/odoo_session_api_client.dart'; + +class OdooPaymentMethodsRepository implements PaymentMethodsRepository { + const OdooPaymentMethodsRepository({required this.apiClient}); + + final OdooSessionApiClient apiClient; + + @override + Future> loadAvailable() async { + try { + final payload = await apiClient.getJson('/pdv_pos/formas_pagamento'); + final records = payload['payment_methods']; + if (records is! List) { + throw const PaymentMethodsException( + 'Resposta de formas de pagamento inválida.', + ); + } + return records + .whereType>() + .map(PaymentMethod.fromJson) + .toList(growable: false); + } on OdooApiException catch (error) { + throw PaymentMethodsException(error.message); + } + } +} diff --git a/pdv/lib/data/repositories/odoo_sale_checkout_repository.dart b/pdv/lib/data/repositories/odoo_sale_checkout_repository.dart new file mode 100644 index 0000000..4368c2c --- /dev/null +++ b/pdv/lib/data/repositories/odoo_sale_checkout_repository.dart @@ -0,0 +1,74 @@ +import 'dart:convert'; + +import '../../domain/entities/cart_item.dart'; +import '../../domain/entities/customer.dart'; +import '../../domain/entities/sale_completion.dart'; +import '../../domain/entities/sale_payment.dart'; +import '../../domain/repositories/sale_checkout_repository.dart'; +import '../datasources/remote/odoo_session_api_client.dart'; + +class OdooSaleCheckoutRepository implements SaleCheckoutRepository { + const OdooSaleCheckoutRepository({required this.apiClient}); + + final OdooSessionApiClient apiClient; + + @override + Future finalizeCashSale({ + required List items, + required List payments, + Customer? customer, + String? customerCpf, + required String checkoutKey, + }) async { + try { + final itemPayload = items.map((item) { + final price = item.product.priceMinorUnits; + if (price == null || item.product.gradeId <= 0) { + throw const SaleCheckoutException( + 'invalid_item', + 'Um produto não possui preço ou grade válida.', + ); + } + return { + 'product_id': item.product.id, + 'grade_id': item.product.gradeId, + 'quantity': item.quantity, + 'unit_price_minor_units': price, + }; + }).toList(growable: false); + + final payload = await apiClient.postForm( + '/pdv_pos/finalizar_venda', + body: { + 'checkout_key': checkoutKey, + 'customer_id': customer?.id.toString() ?? '', + 'customer_cpf': customerCpf ?? '', + 'amount_minor_units': payments + .fold(0, (sum, payment) => sum + payment.amountMinorUnits) + .toString(), + 'items': jsonEncode(itemPayload), + 'payments': jsonEncode(payments + .map((payment) => { + 'condition_form_id': payment.conditionFormId, + 'amount_minor_units': payment.amountMinorUnits, + 'payment_type': payment.paymentType, + }) + .toList(growable: false)), + }, + timeout: const Duration(minutes: 3), + ); + final sale = payload['sale']; + if (sale is! Map) { + throw const SaleCheckoutException( + 'invalid_response', + 'O servidor não retornou os dados da NFC-e.', + ); + } + return SaleCompletion.fromJson(sale); + } on SaleCheckoutException { + rethrow; + } on OdooApiException catch (error) { + throw SaleCheckoutException(error.code, error.message); + } + } +} diff --git a/pdv/lib/data/repositories/odoo_sales_history_repository.dart b/pdv/lib/data/repositories/odoo_sales_history_repository.dart new file mode 100644 index 0000000..0e6ab41 --- /dev/null +++ b/pdv/lib/data/repositories/odoo_sales_history_repository.dart @@ -0,0 +1,32 @@ +import '../../domain/entities/historical_sale.dart'; +import '../../domain/repositories/sales_history_repository.dart'; +import '../datasources/remote/odoo_session_api_client.dart'; + +class OdooSalesHistoryRepository implements SalesHistoryRepository { + const OdooSalesHistoryRepository({required this.apiClient}); + + final OdooSessionApiClient apiClient; + + @override + Future> fetchSales() async { + try { + final payload = await apiClient.getJson('/pdv_pos/historico_vendas'); + final records = payload['sales']; + if (records is! List) { + throw const SalesHistoryException( + 'O servidor retornou um histórico inválido.', + ); + } + return records + .whereType>() + .map(HistoricalSale.fromJson) + .toList(growable: false); + } on OdooApiException catch (error) { + throw SalesHistoryException(error.message); + } on FormatException { + throw const SalesHistoryException( + 'O servidor retornou dados inválidos no histórico.', + ); + } + } +} diff --git a/pdv/lib/data/repositories/shared_preferences_sale_view_preference_repository.dart b/pdv/lib/data/repositories/shared_preferences_sale_view_preference_repository.dart new file mode 100644 index 0000000..8eabe5b --- /dev/null +++ b/pdv/lib/data/repositories/shared_preferences_sale_view_preference_repository.dart @@ -0,0 +1,26 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../domain/entities/sale_view_mode.dart'; +import '../../domain/repositories/sale_view_preference_repository.dart'; + +class SharedPreferencesSaleViewPreferenceRepository + implements SaleViewPreferenceRepository { + const SharedPreferencesSaleViewPreferenceRepository(); + + static const _keyPrefix = 'pdv.sale_view.user.'; + + @override + Future loadForUser(int userId) async { + final preferences = await SharedPreferences.getInstance(); + final value = preferences.getString('$_keyPrefix$userId'); + return value == SaleViewMode.list.name + ? SaleViewMode.list + : SaleViewMode.kanban; + } + + @override + Future saveForUser(int userId, SaleViewMode mode) async { + final preferences = await SharedPreferences.getInstance(); + await preferences.setString('$_keyPrefix$userId', mode.name); + } +} diff --git a/pdv/lib/data/repositories/shared_preferences_settings_repository.dart b/pdv/lib/data/repositories/shared_preferences_settings_repository.dart new file mode 100644 index 0000000..1dbe2a6 --- /dev/null +++ b/pdv/lib/data/repositories/shared_preferences_settings_repository.dart @@ -0,0 +1,34 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../domain/entities/app_settings.dart'; +import '../../domain/repositories/settings_repository.dart'; + +class SharedPreferencesSettingsRepository implements SettingsRepository { + const SharedPreferencesSettingsRepository(); + + static const _serverUrlKey = 'pdv.server_url'; + static const _companyIdentifierKey = 'pdv.company_identifier'; + + @override + Future load() async { + final preferences = await SharedPreferences.getInstance(); + final serverUrl = preferences.getString(_serverUrlKey); + final companyIdentifier = preferences.getString(_companyIdentifierKey); + if (serverUrl == null || companyIdentifier == null) return null; + + return AppSettings( + serverUrl: serverUrl, + companyIdentifier: companyIdentifier, + ); + } + + @override + Future save(AppSettings settings) async { + final preferences = await SharedPreferences.getInstance(); + await preferences.setString(_serverUrlKey, settings.serverUrl); + await preferences.setString( + _companyIdentifierKey, + settings.companyIdentifier, + ); + } +} diff --git a/pdv/lib/domain/entities/app_session.dart b/pdv/lib/domain/entities/app_session.dart new file mode 100644 index 0000000..9735710 --- /dev/null +++ b/pdv/lib/domain/entities/app_session.dart @@ -0,0 +1,13 @@ +class AppSession { + const AppSession({ + required this.userId, + required this.userName, + this.companyId, + this.companyName, + }); + + final int userId; + final String userName; + final int? companyId; + final String? companyName; +} diff --git a/pdv/lib/domain/entities/app_settings.dart b/pdv/lib/domain/entities/app_settings.dart new file mode 100644 index 0000000..cc2b43e --- /dev/null +++ b/pdv/lib/domain/entities/app_settings.dart @@ -0,0 +1,20 @@ +class AppSettings { + const AppSettings({ + required this.serverUrl, + required this.companyIdentifier, + }); + + final String serverUrl; + final String companyIdentifier; + + bool get isConfigured => serverUrl.isNotEmpty && companyIdentifier.isNotEmpty; + + @override + bool operator ==(Object other) => + other is AppSettings && + other.serverUrl == serverUrl && + other.companyIdentifier == companyIdentifier; + + @override + int get hashCode => Object.hash(serverUrl, companyIdentifier); +} diff --git a/pdv/lib/domain/entities/cart_item.dart b/pdv/lib/domain/entities/cart_item.dart new file mode 100644 index 0000000..3bbed9c --- /dev/null +++ b/pdv/lib/domain/entities/cart_item.dart @@ -0,0 +1,13 @@ +import 'product.dart'; + +class CartItem { + const CartItem({required this.product, required this.quantity}); + + final Product product; + final int quantity; + + int? get subtotalMinorUnits { + final unitPrice = product.priceMinorUnits; + return unitPrice == null ? null : unitPrice * quantity; + } +} diff --git a/pdv/lib/domain/entities/customer.dart b/pdv/lib/domain/entities/customer.dart new file mode 100644 index 0000000..9e5773a --- /dev/null +++ b/pdv/lib/domain/entities/customer.dart @@ -0,0 +1,24 @@ +class Customer { + const Customer({ + required this.id, + required this.name, + required this.documentMasked, + }); + + final int id; + final String name; + final String documentMasked; + + factory Customer.fromJson(Map json) { + final id = json['id']; + final name = json['name']; + if (id is! num || name is! String) { + throw const FormatException('Resposta de cliente inválida.'); + } + return Customer( + id: id.toInt(), + name: name, + documentMasked: json['document_masked']?.toString() ?? '', + ); + } +} diff --git a/pdv/lib/domain/entities/department.dart b/pdv/lib/domain/entities/department.dart new file mode 100644 index 0000000..dfe2ffd --- /dev/null +++ b/pdv/lib/domain/entities/department.dart @@ -0,0 +1,15 @@ +class Department { + const Department({required this.id, required this.name}); + + final int id; + final String name; + + factory Department.fromJson(Map json) { + final id = json['id']; + final name = json['name']; + if (id is! num || name is! String) { + throw const FormatException('Resposta de departamento inválida.'); + } + return Department(id: id.toInt(), name: name); + } +} diff --git a/pdv/lib/domain/entities/historical_sale.dart b/pdv/lib/domain/entities/historical_sale.dart new file mode 100644 index 0000000..1a93c32 --- /dev/null +++ b/pdv/lib/domain/entities/historical_sale.dart @@ -0,0 +1,37 @@ +class HistoricalSale { + const HistoricalSale({ + required this.orderNumber, + required this.issueDate, + required this.customerName, + required this.totalMinorUnits, + required this.state, + }); + + final String orderNumber; + final String issueDate; + final String customerName; + final int totalMinorUnits; + final String state; + + factory HistoricalSale.fromJson(Map json) { + final orderNumber = json['order_number']; + final issueDate = json['issue_date']; + final customerName = json['customer_name']; + final total = json['total']; + final state = json['state']; + if (orderNumber is! String || + issueDate is! String || + customerName is! String || + total is! num || + state is! String) { + throw const FormatException('Pedido inválido no histórico de vendas.'); + } + return HistoricalSale( + orderNumber: orderNumber, + issueDate: issueDate, + customerName: customerName, + totalMinorUnits: (total * 100).round(), + state: state, + ); + } +} diff --git a/pdv/lib/domain/entities/payment_method.dart b/pdv/lib/domain/entities/payment_method.dart new file mode 100644 index 0000000..69b63c2 --- /dev/null +++ b/pdv/lib/domain/entities/payment_method.dart @@ -0,0 +1,35 @@ +class PaymentMethod { + const PaymentMethod({ + required this.id, + required this.name, + this.paymentType, + this.conditionId, + this.conditionType, + this.installments, + }); + + final int id; + final String name; + final String? paymentType; + final int? conditionId; + final String? conditionType; + final int? installments; + + factory PaymentMethod.fromJson(Map json) { + final id = json['id']; + final name = json['name']; + if (id is! num || name is! String) { + throw const FormatException('Resposta de forma de pagamento inválida.'); + } + return PaymentMethod( + id: id.toInt(), + name: name, + paymentType: json['payment_type']?.toString(), + conditionId: _asInt(json['condition_id']), + conditionType: json['condition_type']?.toString(), + installments: _asInt(json['installments']), + ); + } + + static int? _asInt(dynamic value) => value is num ? value.toInt() : null; +} diff --git a/pdv/lib/domain/entities/pos_device.dart b/pdv/lib/domain/entities/pos_device.dart new file mode 100644 index 0000000..f38eb7e --- /dev/null +++ b/pdv/lib/domain/entities/pos_device.dart @@ -0,0 +1,15 @@ +class PosDevice { + const PosDevice({ + required this.platform, + this.serial, + this.model, + this.brand, + }); + + final String platform; + final String? serial; + final String? model; + final String? brand; + + bool get requiresLicense => platform.toLowerCase() == 'android'; +} diff --git a/pdv/lib/domain/entities/product.dart b/pdv/lib/domain/entities/product.dart new file mode 100644 index 0000000..28eb70b --- /dev/null +++ b/pdv/lib/domain/entities/product.dart @@ -0,0 +1,73 @@ +class Product { + const Product({ + required this.id, + this.gradeId = 0, + required this.code, + required this.grade, + required this.name, + required this.departmentCode, + required this.writeDate, + this.priceMinorUnits, + this.stock, + this.imageBase64, + }); + + final int id; + final int gradeId; + final String code; + final String grade; + final String name; + final int departmentCode; + final String writeDate; + final int? priceMinorUnits; + final num? stock; + final String? imageBase64; + + String get cartKey => '$id:$grade'; + + factory Product.fromJson(Map json) { + final id = json['id']; + final departmentCode = json['departamento_id']; + if (id is! num || departmentCode is! num) { + throw const FormatException('Resposta de produto inválida.'); + } + + return Product( + id: id.toInt(), + gradeId: json['grade_id'] is num ? (json['grade_id'] as num).toInt() : 0, + code: json['codigo']?.toString() ?? '', + grade: json['grade']?.toString() ?? '', + name: json['descricao']?.toString() ?? '', + departmentCode: departmentCode.toInt(), + writeDate: json['write_date']?.toString() ?? '', + priceMinorUnits: _toMinorUnits(json['preco']), + stock: _number(json['qtdEmEstoque']), + imageBase64: json['foto'] is String && (json['foto'] as String).isNotEmpty + ? json['foto'] as String + : null, + ); + } + + static int? _toMinorUnits(dynamic value) { + if (value == null || value is bool) return null; + final normalized = value.toString().replaceAll(',', '.'); + final match = RegExp(r'^(-?)(\d+)(?:\.(\d+))?$').firstMatch(normalized); + if (match == null) return null; + + final isNegative = match.group(1) == '-'; + final whole = int.tryParse(match.group(2)!); + if (whole == null) return null; + + final fraction = match.group(3) ?? ''; + final centsText = fraction.padRight(2, '0'); + var minorUnits = whole * 100 + int.parse(centsText.substring(0, 2)); + if (fraction.length > 2 && int.parse(fraction[2]) >= 5) minorUnits++; + return isNegative ? -minorUnits : minorUnits; + } + + static num? _number(dynamic value) { + if (value is num) return value; + if (value is String) return num.tryParse(value.replaceAll(',', '.')); + return null; + } +} diff --git a/pdv/lib/domain/entities/sale_completion.dart b/pdv/lib/domain/entities/sale_completion.dart new file mode 100644 index 0000000..c339760 --- /dev/null +++ b/pdv/lib/domain/entities/sale_completion.dart @@ -0,0 +1,44 @@ +class SaleCompletion { + const SaleCompletion({ + required this.orderNumber, + required this.invoiceId, + required this.invoiceNumber, + required this.invoiceSeries, + this.invoiceState = '', + this.invoiceContingency = false, + this.invoiceMessage = '', + }); + + final String orderNumber; + final int invoiceId; + final String invoiceNumber; + final String invoiceSeries; + final String invoiceState; + final bool invoiceContingency; + final String invoiceMessage; + + factory SaleCompletion.fromJson(Map json) { + final orderNumber = json['order_number']; + final invoiceId = json['invoice_id']; + final invoiceNumber = json['invoice_number']; + final invoiceSeries = json['invoice_series']; + final invoiceState = json['invoice_state']; + final invoiceContingency = json['invoice_contingency']; + final invoiceMessage = json['invoice_message']; + if (orderNumber is! String || + invoiceId is! num || + invoiceNumber == null || + invoiceSeries == null) { + throw const FormatException('Resposta de finalização inválida.'); + } + return SaleCompletion( + orderNumber: orderNumber, + invoiceId: invoiceId.toInt(), + invoiceNumber: invoiceNumber.toString(), + invoiceSeries: invoiceSeries.toString(), + invoiceState: invoiceState?.toString() ?? '', + invoiceContingency: invoiceContingency == true, + invoiceMessage: invoiceMessage?.toString() ?? '', + ); + } +} diff --git a/pdv/lib/domain/entities/sale_payment.dart b/pdv/lib/domain/entities/sale_payment.dart new file mode 100644 index 0000000..f76b9a7 --- /dev/null +++ b/pdv/lib/domain/entities/sale_payment.dart @@ -0,0 +1,11 @@ +class SalePayment { + const SalePayment({ + required this.conditionFormId, + required this.amountMinorUnits, + required this.paymentType, + }); + + final int conditionFormId; + final int amountMinorUnits; + final String paymentType; +} diff --git a/pdv/lib/domain/entities/sale_view_mode.dart b/pdv/lib/domain/entities/sale_view_mode.dart new file mode 100644 index 0000000..d7b75c0 --- /dev/null +++ b/pdv/lib/domain/entities/sale_view_mode.dart @@ -0,0 +1 @@ +enum SaleViewMode { list, kanban } diff --git a/pdv/lib/domain/repositories/auth_repository.dart b/pdv/lib/domain/repositories/auth_repository.dart new file mode 100644 index 0000000..70a1d63 --- /dev/null +++ b/pdv/lib/domain/repositories/auth_repository.dart @@ -0,0 +1,28 @@ +import '../entities/app_settings.dart'; +import '../entities/app_session.dart'; +import '../entities/pos_device.dart'; + +abstract interface class AuthRepository { + bool get isAuthenticated; + + AppSession? get currentSession; + + Future authenticate({ + required String username, + required String password, + required AppSettings settings, + required PosDevice device, + required String appVersion, + }); + + Future logout(); +} + +class AuthUnavailableException implements Exception { + const AuthUnavailableException(this.message); + + final String message; + + @override + String toString() => message; +} diff --git a/pdv/lib/domain/repositories/cart_repository.dart b/pdv/lib/domain/repositories/cart_repository.dart new file mode 100644 index 0000000..0ab1c83 --- /dev/null +++ b/pdv/lib/domain/repositories/cart_repository.dart @@ -0,0 +1,84 @@ +import 'package:flutter/foundation.dart'; + +import '../entities/cart_item.dart'; +import '../entities/product.dart'; + +abstract interface class CartRepository implements Listenable { + List get items; + + int get itemCount; + + int? get totalMinorUnits; + + void addProduct(Product product); + + void increaseQuantity(Product product); + + void decreaseQuantity(Product product); + + void removeProduct(Product product); + + void clear(); +} + +class InMemoryCartRepository extends ChangeNotifier implements CartRepository { + final Map _items = {}; + + @override + List get items => List.unmodifiable(_items.values); + + @override + int get itemCount => + _items.values.fold(0, (count, item) => count + item.quantity); + + @override + int? get totalMinorUnits { + if (_items.values.any((item) => item.product.priceMinorUnits == null)) { + return null; + } + return _items.values.fold( + 0, + (total, item) => total + item.product.priceMinorUnits! * item.quantity, + ); + } + + @override + void addProduct(Product product) { + increaseQuantity(product); + } + + @override + void increaseQuantity(Product product) { + final key = product.cartKey; + final existing = _items[key]; + _items[key] = CartItem( + product: product, + quantity: (existing?.quantity ?? 0) + 1, + ); + notifyListeners(); + } + + @override + void decreaseQuantity(Product product) { + final key = product.cartKey; + final existing = _items[key]; + if (existing == null || existing.quantity <= 1) return; + _items[key] = CartItem( + product: existing.product, + quantity: existing.quantity - 1, + ); + notifyListeners(); + } + + @override + void removeProduct(Product product) { + if (_items.remove(product.cartKey) != null) notifyListeners(); + } + + @override + void clear() { + if (_items.isEmpty) return; + _items.clear(); + notifyListeners(); + } +} diff --git a/pdv/lib/domain/repositories/catalog_repository.dart b/pdv/lib/domain/repositories/catalog_repository.dart new file mode 100644 index 0000000..cc19cf0 --- /dev/null +++ b/pdv/lib/domain/repositories/catalog_repository.dart @@ -0,0 +1,19 @@ +import '../entities/department.dart'; +import '../entities/product.dart'; + +abstract interface class CatalogRepository { + Future> fetchDepartments(); + + Future> fetchProductsByDepartment(int departmentId); + + Future fetchProductByBarcode(String barcode); +} + +class CatalogException implements Exception { + const CatalogException(this.message); + + final String message; + + @override + String toString() => message; +} diff --git a/pdv/lib/domain/repositories/connection_tester.dart b/pdv/lib/domain/repositories/connection_tester.dart new file mode 100644 index 0000000..3388efc --- /dev/null +++ b/pdv/lib/domain/repositories/connection_tester.dart @@ -0,0 +1,13 @@ +class ConnectionTestResult { + const ConnectionTestResult({ + required this.isAvailable, + required this.message, + }); + + final bool isAvailable; + final String message; +} + +abstract interface class ConnectionTester { + Future test(Uri serverUri); +} diff --git a/pdv/lib/domain/repositories/customer_repository.dart b/pdv/lib/domain/repositories/customer_repository.dart new file mode 100644 index 0000000..a27eed4 --- /dev/null +++ b/pdv/lib/domain/repositories/customer_repository.dart @@ -0,0 +1,14 @@ +import '../entities/customer.dart'; + +abstract interface class CustomerRepository { + Future> search(String query); +} + +class CustomerSearchException implements Exception { + const CustomerSearchException(this.message); + + final String message; + + @override + String toString() => message; +} diff --git a/pdv/lib/domain/repositories/payment_methods_repository.dart b/pdv/lib/domain/repositories/payment_methods_repository.dart new file mode 100644 index 0000000..f897bcc --- /dev/null +++ b/pdv/lib/domain/repositories/payment_methods_repository.dart @@ -0,0 +1,14 @@ +import '../entities/payment_method.dart'; + +abstract interface class PaymentMethodsRepository { + Future> loadAvailable(); +} + +class PaymentMethodsException implements Exception { + const PaymentMethodsException(this.message); + + final String message; + + @override + String toString() => message; +} diff --git a/pdv/lib/domain/repositories/sale_checkout_repository.dart b/pdv/lib/domain/repositories/sale_checkout_repository.dart new file mode 100644 index 0000000..1fabdda --- /dev/null +++ b/pdv/lib/domain/repositories/sale_checkout_repository.dart @@ -0,0 +1,24 @@ +import '../entities/cart_item.dart'; +import '../entities/customer.dart'; +import '../entities/sale_completion.dart'; +import '../entities/sale_payment.dart'; + +abstract interface class SaleCheckoutRepository { + Future finalizeCashSale({ + required List items, + required List payments, + Customer? customer, + String? customerCpf, + required String checkoutKey, + }); +} + +class SaleCheckoutException implements Exception { + const SaleCheckoutException(this.code, this.message); + + final String code; + final String message; + + @override + String toString() => message; +} diff --git a/pdv/lib/domain/repositories/sale_view_preference_repository.dart b/pdv/lib/domain/repositories/sale_view_preference_repository.dart new file mode 100644 index 0000000..83e6407 --- /dev/null +++ b/pdv/lib/domain/repositories/sale_view_preference_repository.dart @@ -0,0 +1,7 @@ +import '../entities/sale_view_mode.dart'; + +abstract interface class SaleViewPreferenceRepository { + Future loadForUser(int userId); + + Future saveForUser(int userId, SaleViewMode mode); +} diff --git a/pdv/lib/domain/repositories/sales_history_repository.dart b/pdv/lib/domain/repositories/sales_history_repository.dart new file mode 100644 index 0000000..ddf2187 --- /dev/null +++ b/pdv/lib/domain/repositories/sales_history_repository.dart @@ -0,0 +1,14 @@ +import '../entities/historical_sale.dart'; + +abstract interface class SalesHistoryRepository { + Future> fetchSales(); +} + +class SalesHistoryException implements Exception { + const SalesHistoryException(this.message); + + final String message; + + @override + String toString() => message; +} diff --git a/pdv/lib/domain/repositories/settings_repository.dart b/pdv/lib/domain/repositories/settings_repository.dart new file mode 100644 index 0000000..0cdb76f --- /dev/null +++ b/pdv/lib/domain/repositories/settings_repository.dart @@ -0,0 +1,7 @@ +import '../entities/app_settings.dart'; + +abstract interface class SettingsRepository { + Future load(); + + Future save(AppSettings settings); +} diff --git a/pdv/lib/features/cart/presentation/cart_screen.dart b/pdv/lib/features/cart/presentation/cart_screen.dart new file mode 100644 index 0000000..b267d6b --- /dev/null +++ b/pdv/lib/features/cart/presentation/cart_screen.dart @@ -0,0 +1,210 @@ +import 'package:flutter/material.dart'; + +import '../../../app/app_services.dart'; +import '../../../app/router/app_router.dart'; +import '../../../core/utils/currency_formatter.dart'; +import '../../../core/widgets/app_button.dart'; +import '../../../core/widgets/empty_view.dart'; +import '../../../domain/entities/cart_item.dart'; + +class CartScreen extends StatelessWidget { + const CartScreen({required this.services, super.key}); + + final AppServices services; + + Future _confirmClear(BuildContext context) async { + final shouldClear = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Limpar carrinho?'), + content: const Text('Todos os produtos serão removidos do carrinho.'), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Cancelar'), + ), + FilledButton( + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Limpar'), + ), + ], + ), + ); + if (shouldClear == true) services.cartRepository.clear(); + } + + Widget _buildCartItem(BuildContext context, CartItem item) { + final repository = services.cartRepository; + return Card( + margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 5), + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + item.product.name, + style: Theme.of(context).textTheme.titleMedium, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 4), + Text( + 'Código ${item.product.code} · Grade ${item.product.grade}', + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Unitário: ${CurrencyFormatter.formatBrl(item.product.priceMinorUnits)}', + ), + Text( + 'Subtotal: ${CurrencyFormatter.formatBrl(item.subtotalMinorUnits)}', + style: const TextStyle(fontWeight: FontWeight.w600), + ), + ], + ), + ), + IconButton( + key: Key('decrease-${item.product.cartKey}'), + tooltip: 'Diminuir quantidade', + onPressed: item.quantity <= 1 + ? null + : () => repository.decreaseQuantity(item.product), + icon: const Icon(Icons.remove_circle_outline), + ), + Text( + '${item.quantity}', + key: Key('quantity-${item.product.cartKey}'), + style: Theme.of(context).textTheme.titleMedium, + ), + IconButton( + key: Key('increase-${item.product.cartKey}'), + tooltip: 'Aumentar quantidade', + onPressed: () => repository.increaseQuantity(item.product), + icon: const Icon(Icons.add_circle_outline), + ), + IconButton( + key: Key('remove-${item.product.cartKey}'), + tooltip: 'Remover produto', + onPressed: () => repository.removeProduct(item.product), + icon: Icon( + Icons.delete_outline, + color: Theme.of(context).colorScheme.error, + ), + ), + ], + ), + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Carrinho'), + actions: [ + AnimatedBuilder( + animation: services.cartRepository, + builder: (context, _) => IconButton( + key: const Key('clear-cart-button'), + tooltip: 'Limpar carrinho', + onPressed: services.cartRepository.itemCount == 0 + ? null + : () => _confirmClear(context), + icon: const Icon(Icons.delete_sweep_outlined), + ), + ), + ], + ), + body: AnimatedBuilder( + animation: services.cartRepository, + builder: (context, _) { + final items = services.cartRepository.items; + if (items.isEmpty) { + return Column( + children: [ + const Expanded( + child: EmptyView( + title: 'Carrinho vazio', + message: 'Adicione produtos na tela de venda.', + icon: Icons.shopping_cart_outlined, + ), + ), + Padding( + padding: const EdgeInsets.all(16), + child: AppButton( + label: 'Voltar para venda', + icon: Icons.storefront_outlined, + onPressed: () => Navigator.of(context).pop(), + ), + ), + ], + ); + } + + final total = services.cartRepository.totalMinorUnits; + return Column( + children: [ + Expanded( + child: ListView.builder( + padding: const EdgeInsets.only(top: 8, bottom: 8), + itemCount: items.length, + itemBuilder: (context, index) => + _buildCartItem(context, items[index]), + ), + ), + Material( + elevation: 4, + color: Theme.of(context).colorScheme.surface, + child: SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + const Expanded( + child: Text( + 'Total (prévia)', + style: TextStyle(fontWeight: FontWeight.w600), + ), + ), + Text( + total == null + ? 'Total indisponível' + : CurrencyFormatter.formatBrl(total), + key: const Key('cart-total'), + style: Theme.of(context).textTheme.titleLarge, + ), + ], + ), + const SizedBox(height: 10), + AppButton( + label: 'Pagamento', + icon: Icons.payments_outlined, + onPressed: () => Navigator.of(context) + .pushNamed(AppRoutes.payment), + ), + ], + ), + ), + ), + ), + ], + ); + }, + ), + ); + } +} diff --git a/pdv/lib/features/customer_search/presentation/customer_search_screen.dart b/pdv/lib/features/customer_search/presentation/customer_search_screen.dart new file mode 100644 index 0000000..466b757 --- /dev/null +++ b/pdv/lib/features/customer_search/presentation/customer_search_screen.dart @@ -0,0 +1,146 @@ +import 'package:flutter/material.dart'; + +import '../../../app/app_services.dart'; +import '../../../core/widgets/empty_view.dart'; +import '../../../core/widgets/error_view.dart'; +import '../../../core/widgets/loading_view.dart'; +import '../../../domain/entities/customer.dart'; +import '../../../domain/repositories/customer_repository.dart'; + +class CustomerSearchScreen extends StatefulWidget { + const CustomerSearchScreen({required this.services, super.key}); + + final AppServices services; + + @override + State createState() => _CustomerSearchScreenState(); +} + +class _CustomerSearchScreenState extends State { + final _queryController = TextEditingController(); + List _customers = []; + bool _loading = false; + bool _hasSearched = false; + String? _errorMessage; + + @override + void dispose() { + _queryController.dispose(); + super.dispose(); + } + + Future _search() async { + final query = _queryController.text.trim(); + if (query.isEmpty || _loading) return; + setState(() { + _loading = true; + _hasSearched = true; + _errorMessage = null; + _customers = []; + }); + try { + final customers = await widget.services.customerRepository.search(query); + if (mounted) setState(() => _customers = customers); + } on CustomerSearchException catch (error) { + if (mounted) setState(() => _errorMessage = error.message); + } catch (_) { + if (mounted) { + setState(() => _errorMessage = 'Não foi possível pesquisar clientes.'); + } + } finally { + if (mounted) setState(() => _loading = false); + } + } + + void _select(Customer customer) { + Navigator.of(context).pop(customer); + } + + Widget _buildResults() { + if (_loading) return const LoadingView(message: 'Pesquisando clientes...'); + if (_errorMessage != null) { + return ErrorView(message: _errorMessage!, onRetry: _search); + } + if (!_hasSearched) { + return const EmptyView( + title: 'Pesquisar cliente', + message: 'Informe o nome ou CPF do cliente.', + icon: Icons.person_search_outlined, + ); + } + if (_customers.isEmpty) { + return const EmptyView( + title: 'Nenhum cliente encontrado', + message: 'Tente outro nome ou CPF.', + icon: Icons.person_off_outlined, + ); + } + return ListView.separated( + padding: const EdgeInsets.all(12), + itemCount: _customers.length, + separatorBuilder: (_, __) => const SizedBox(height: 6), + itemBuilder: (context, index) { + final customer = _customers[index]; + return Card( + child: ListTile( + key: Key('customer-${customer.id}'), + title: Text(customer.name), + subtitle: customer.documentMasked.isEmpty + ? null + : Text(customer.documentMasked), + trailing: const Icon(Icons.chevron_right), + onTap: () => _select(customer), + ), + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Consulta de cliente')), + body: SafeArea( + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Row( + children: [ + Expanded( + child: TextField( + key: const Key('customer-search-query'), + controller: _queryController, + enabled: !_loading, + textInputAction: TextInputAction.search, + onSubmitted: (_) => _search(), + decoration: const InputDecoration( + labelText: 'Nome ou CPF', + prefixIcon: Icon(Icons.search), + ), + ), + ), + const SizedBox(width: 10), + IconButton.filledTonal( + key: const Key('customer-search-button'), + tooltip: 'Pesquisar cliente', + constraints: + const BoxConstraints.tightFor(width: 52, height: 52), + onPressed: _loading ? null : _search, + icon: _loading + ? const SizedBox.square( + dimension: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.search), + ), + ], + ), + ), + Expanded(child: _buildResults()), + ], + ), + ), + ); + } +} diff --git a/pdv/lib/features/login/presentation/login_screen.dart b/pdv/lib/features/login/presentation/login_screen.dart new file mode 100644 index 0000000..80fd068 --- /dev/null +++ b/pdv/lib/features/login/presentation/login_screen.dart @@ -0,0 +1,244 @@ +import 'dart:developer' as developer; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../app/app_services.dart'; +import '../../../app/router/app_router.dart'; +import '../../../core/widgets/app_button.dart'; +import '../../../domain/repositories/auth_repository.dart'; + +class LoginScreen extends StatefulWidget { + const LoginScreen({required this.services, super.key}); + + final AppServices services; + + @override + State createState() => _LoginScreenState(); +} + +class _LoginScreenState extends State { + final _formKey = GlobalKey(); + final _usernameController = TextEditingController(); + final _passwordController = TextEditingController(); + bool _obscurePassword = true; + bool _submitting = false; + late final Future _appVersion; + + @override + void initState() { + super.initState(); + _appVersion = widget.services.appVersionProvider.getVersion(); + } + + @override + void dispose() { + _usernameController.dispose(); + _passwordController.dispose(); + super.dispose(); + } + + Future _submit() async { + if (_submitting || !_formKey.currentState!.validate()) return; + setState(() => _submitting = true); + + try { + final settings = await widget.services.settingsRepository.load(); + if (settings?.isConfigured != true) { + _showMessage('Configure o servidor pela engrenagem antes de entrar.'); + return; + } + + final device = await widget.services.posDeviceProvider.getDevice(); + final appVersion = await widget.services.appVersionProvider.getVersion(); + await widget.services.authRepository.authenticate( + username: _usernameController.text.trim(), + password: _passwordController.text, + settings: settings!, + device: device, + appVersion: appVersion, + ); + if (mounted) { + Navigator.of(context).pushNamedAndRemoveUntil( + AppRoutes.menu, + (route) => false, + ); + } + } on UnsupportedError catch (error) { + developer.log( + 'Login bloqueado pela plataforma do dispositivo.', + name: 'pdv.auth', + ); + _showMessage(error.message.toString()); + } on AuthUnavailableException catch (error) { + _showMessage(error.message); + } catch (error, stackTrace) { + developer.log( + 'Falha ao preparar login do PDV: ${error.runtimeType}.', + name: 'pdv.auth', + stackTrace: stackTrace, + ); + _showMessage( + 'Não foi possível autenticar. Verifique os dados e tente novamente.'); + } finally { + if (mounted) setState(() => _submitting = false); + } + } + + Future _exit() async { + await widget.services.authRepository.logout(); + await SystemNavigator.pop(); + } + + void _openSettings() { + Navigator.of(context).pushNamed(AppRoutes.settings); + } + + void _showMessage(String message) { + if (!mounted) return; + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(message))); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + automaticallyImplyLeading: false, + title: const Text('PDV'), + ), + body: SafeArea( + child: Column( + children: [ + Padding( + padding: const EdgeInsets.only(left: 16, right: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + FutureBuilder( + future: _appVersion, + builder: (context, snapshot) { + if (!snapshot.hasData || snapshot.hasError) { + return const SizedBox.shrink(); + } + return Text( + 'Versão: ${snapshot.data}', + key: const Key('app-version'), + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 11, + ), + ); + }, + ), + IconButton( + key: const Key('settings-button'), + tooltip: 'Configuração', + onPressed: _submitting ? null : _openSettings, + icon: const Icon(Icons.settings_outlined), + ), + ], + ), + ), + Expanded( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 440), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Icon( + Icons.point_of_sale_rounded, + size: 64, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(height: 20), + Text( + 'Acesso ao PDV', + textAlign: TextAlign.center, + style: Theme.of(context) + .textTheme + .headlineSmall + ?.copyWith( + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 28), + TextFormField( + key: const Key('login-username'), + controller: _usernameController, + enabled: !_submitting, + textInputAction: TextInputAction.next, + autocorrect: false, + decoration: const InputDecoration( + labelText: 'Usuário', + prefixIcon: Icon(Icons.person_outline), + ), + validator: (value) => + value == null || value.trim().isEmpty + ? 'Informe o usuário.' + : null, + ), + const SizedBox(height: 16), + TextFormField( + key: const Key('login-password'), + controller: _passwordController, + enabled: !_submitting, + obscureText: _obscurePassword, + textInputAction: TextInputAction.done, + onFieldSubmitted: (_) => _submit(), + decoration: InputDecoration( + labelText: 'Senha', + prefixIcon: const Icon(Icons.lock_outline), + suffixIcon: IconButton( + tooltip: _obscurePassword + ? 'Mostrar senha' + : 'Ocultar senha', + onPressed: () => setState( + () => _obscurePassword = !_obscurePassword, + ), + icon: Icon( + _obscurePassword + ? Icons.visibility_outlined + : Icons.visibility_off_outlined, + ), + ), + ), + validator: (value) => value == null || value.isEmpty + ? 'Informe a senha.' + : null, + ), + const SizedBox(height: 24), + AppButton( + label: 'Entrar', + icon: Icons.login, + onPressed: _submitting ? null : _submit, + ), + if (_submitting) ...[ + const SizedBox(height: 16), + const Center(child: CircularProgressIndicator()), + ], + const SizedBox(height: 12), + TextButton.icon( + onPressed: _submitting ? null : _exit, + icon: const Icon(Icons.exit_to_app), + label: const Text('Sair'), + ), + ], + ), + ), + ), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/pdv/lib/features/menu/presentation/menu_screen.dart b/pdv/lib/features/menu/presentation/menu_screen.dart new file mode 100644 index 0000000..5299eba --- /dev/null +++ b/pdv/lib/features/menu/presentation/menu_screen.dart @@ -0,0 +1,164 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../app/app_services.dart'; +import '../../../app/router/app_router.dart'; + +class MenuScreen extends StatefulWidget { + const MenuScreen({required this.services, super.key}); + + final AppServices services; + + @override + State createState() => _MenuScreenState(); +} + +class _MenuScreenState extends State { + bool _loggingOut = false; + + Future _logout() async { + if (_loggingOut) return; + setState(() => _loggingOut = true); + await widget.services.authRepository.logout(); + if (!mounted) return; + Navigator.of(context).pushNamedAndRemoveUntil( + AppRoutes.login, + (_) => false, + ); + } + + Future _exit() => SystemNavigator.pop(); + + @override + Widget build(BuildContext context) { + final session = widget.services.authRepository.currentSession; + final companyId = session?.companyId; + final companyName = session?.companyName; + final companyDescription = [ + if (companyId != null) companyId.toString(), + if (companyName != null && companyName.trim().isNotEmpty) + companyName.trim(), + ].join(' - '); + + final actions = [ + _MenuAction( + label: 'Venda', + icon: Icons.point_of_sale_outlined, + onPressed: () => Navigator.of(context).pushNamed(AppRoutes.sale), + ), + _MenuAction( + label: 'Histórico de vendas', + icon: Icons.receipt_long_outlined, + onPressed: () => + Navigator.of(context).pushNamed(AppRoutes.salesHistory), + ), + _MenuAction( + label: _loggingOut ? 'Saindo...' : 'Log out', + icon: Icons.logout, + onPressed: _loggingOut ? null : _logout, + ), + _MenuAction( + label: 'Sair', + icon: Icons.power_settings_new, + onPressed: _exit, + ), + ]; + + return Scaffold( + appBar: AppBar( + automaticallyImplyLeading: false, + title: const Text('Menu do PDV'), + ), + body: SafeArea( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 760), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Card( + child: ListTile( + leading: const CircleAvatar( + child: Icon(Icons.person_outline), + ), + title: Text( + session?.userName ?? 'Usuário', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context) + .textTheme + .titleMedium + ?.copyWith(fontWeight: FontWeight.bold), + ), + subtitle: Text( + companyDescription.isEmpty + ? 'Empresa não informada' + : 'Empresa: $companyDescription', + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ), + ), + ), + Expanded( + child: GridView.builder( + padding: const EdgeInsets.all(16), + itemCount: actions.length, + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + crossAxisSpacing: 16, + mainAxisSpacing: 16, + childAspectRatio: 1, + ), + itemBuilder: (context, index) { + final action = actions[index]; + return Card( + clipBehavior: Clip.antiAlias, + child: InkWell( + key: Key('menu-${index + 1}'), + onTap: action.onPressed, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(action.icon, size: 48), + const SizedBox(height: 12), + Text( + action.label, + textAlign: TextAlign.center, + style: Theme.of(context) + .textTheme + .titleMedium + ?.copyWith(fontWeight: FontWeight.w600), + ), + ], + ), + ), + ), + ); + }, + ), + ), + ], + ), + ), + ), + ), + ); + } +} + +class _MenuAction { + const _MenuAction({ + required this.label, + required this.icon, + required this.onPressed, + }); + + final String label; + final IconData icon; + final VoidCallback? onPressed; +} diff --git a/pdv/lib/features/payment/presentation/payment_screen.dart b/pdv/lib/features/payment/presentation/payment_screen.dart new file mode 100644 index 0000000..87c26bb --- /dev/null +++ b/pdv/lib/features/payment/presentation/payment_screen.dart @@ -0,0 +1,679 @@ +import 'package:flutter/material.dart'; + +import '../../../app/app_services.dart'; +import '../../../app/router/app_router.dart'; +import '../../../core/utils/currency_formatter.dart'; +import '../../../core/widgets/app_button.dart'; +import '../../../core/widgets/empty_view.dart'; +import '../../../core/widgets/error_view.dart'; +import '../../../core/widgets/loading_view.dart'; +import '../../../domain/entities/customer.dart'; +import '../../../domain/entities/payment_method.dart'; +import '../../../domain/entities/sale_payment.dart'; +import '../../../domain/repositories/payment_methods_repository.dart'; +import '../../../domain/repositories/sale_checkout_repository.dart'; + +enum _PaymentCategory { cash, pix, credit, debit } + +class _PaymentAllocation { + const _PaymentAllocation({required this.method, required this.amountMinor}); + + final PaymentMethod method; + final int amountMinor; + + bool get isCash => method.paymentType == '01'; +} + +extension _PaymentCategoryPresentation on _PaymentCategory { + String get label { + switch (this) { + case _PaymentCategory.cash: + return 'Dinheiro'; + case _PaymentCategory.pix: + return 'PIX'; + case _PaymentCategory.credit: + return 'Cartão de Crédito'; + case _PaymentCategory.debit: + return 'Cartão de Débito'; + } + } + + IconData get icon { + switch (this) { + case _PaymentCategory.cash: + return Icons.payments_outlined; + case _PaymentCategory.pix: + return Icons.qr_code_2_outlined; + case _PaymentCategory.credit: + return Icons.credit_card; + case _PaymentCategory.debit: + return Icons.credit_card_outlined; + } + } +} + +class PaymentScreen extends StatefulWidget { + const PaymentScreen({required this.services, super.key}); + + final AppServices services; + + @override + State createState() => _PaymentScreenState(); +} + +class _PaymentScreenState extends State { + List _methods = []; + bool _loading = true; + String? _errorMessage; + String? _checkoutError; + String? _customerCpf; + final List<_PaymentAllocation> _allocations = []; + Customer? _customer; + late final String _checkoutKey; + bool _finalizing = false; + + @override + void initState() { + super.initState(); + final userId = widget.services.authRepository.currentSession?.userId ?? 0; + _checkoutKey = 'pdv-$userId-${DateTime.now().microsecondsSinceEpoch}'; + _loadPaymentMethods(); + } + + Future _loadPaymentMethods() async { + setState(() { + _loading = true; + _errorMessage = null; + }); + try { + final methods = + await widget.services.paymentMethodsRepository.loadAvailable(); + if (!mounted) return; + setState(() { + _methods = methods; + _loading = false; + }); + } on PaymentMethodsException catch (error) { + if (mounted) { + setState(() { + _errorMessage = error.message; + _loading = false; + }); + } + } catch (_) { + if (mounted) { + setState(() { + _errorMessage = 'Não foi possível carregar formas de pagamento.'; + _loading = false; + }); + } + } + } + + Future _includeCustomer() async { + final customer = await Navigator.of(context) + .pushNamed(AppRoutes.customerSearch); + if (mounted && customer != null) setState(() => _customer = customer); + } + + bool _canFinalize(int? total) => + !_finalizing && + total != null && + _allocations.isNotEmpty && + _allocatedMinorUnits == total && + _allocations.every((allocation) => allocation.isCash); + + Future _requestCustomerCpf() async { + final controller = TextEditingController(); + String? errorMessage; + final cpf = await showDialog( + context: context, + builder: (dialogContext) => StatefulBuilder( + builder: (context, setDialogState) => AlertDialog( + title: const Text('CPF/CNPJ para NFC-e'), + content: TextField( + controller: controller, + autofocus: true, + keyboardType: TextInputType.number, + decoration: InputDecoration( + labelText: 'CPF ou CNPJ', + errorText: errorMessage, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Cancelar'), + ), + FilledButton( + onPressed: () { + final digits = controller.text.replaceAll(RegExp(r'\D'), ''); + if (digits.length != 11 && digits.length != 14) { + setDialogState( + () => errorMessage = 'Informe um CPF ou CNPJ válido.', + ); + return; + } + Navigator.of(dialogContext).pop(digits); + }, + child: const Text('Continuar'), + ), + ], + ), + ), + ); + controller.dispose(); + return cpf; + } + + Future _finalizeCashSale(int? total) async { + if (!_canFinalize(total) || total == null) return; + setState(() { + _finalizing = true; + _checkoutError = null; + }); + + var cpf = _customerCpf; + try { + var completion = + await widget.services.saleCheckoutRepository.finalizeCashSale( + items: widget.services.cartRepository.items, + payments: _allocations + .map( + (allocation) => SalePayment( + conditionFormId: allocation.method.id, + amountMinorUnits: allocation.amountMinor, + paymentType: allocation.method.paymentType ?? '', + ), + ) + .toList(growable: false), + customer: _customer, + customerCpf: cpf, + checkoutKey: _checkoutKey, + ); + if (!mounted) return; + await Navigator.of(context).pushReplacementNamed( + AppRoutes.saleComplete, + arguments: completion, + ); + } on SaleCheckoutException catch (error) { + if (error.code == 'customer_cpf_required' && _customer == null) { + cpf = await _requestCustomerCpf(); + if (cpf != null && mounted) { + setState(() => _customerCpf = cpf); + setState(() => _finalizing = false); + await _finalizeCashSale(total); + return; + } + } + if (mounted) setState(() => _checkoutError = error.message); + } catch (_) { + if (mounted) { + setState(() { + _checkoutError = 'Não foi possível concluir a venda no Odoo.'; + }); + } + } finally { + if (mounted && _finalizing) setState(() => _finalizing = false); + } + } + + _PaymentCategory? _categoryFor(PaymentMethod method) { + switch (method.paymentType) { + case '01': + return _PaymentCategory.cash; + case '17': + case '20': + case '23': + return _PaymentCategory.pix; + case '03': + return _PaymentCategory.credit; + case '04': + return _PaymentCategory.debit; + default: + return null; + } + } + + List _methodsFor(_PaymentCategory category) => _methods + .where((method) => _categoryFor(method) == category) + .toList(growable: false); + + int get _allocatedMinorUnits => _allocations.fold( + 0, + (total, allocation) => total + allocation.amountMinor, + ); + + Future _addPayment(_PaymentCategory category, int? total) async { + if (total == null) return; + final options = _methodsFor(category); + if (options.isEmpty) return; + final remaining = total - _allocatedMinorUnits; + if (remaining <= 0) return; + + var selectedMethod = options.first; + String? validationMessage; + final amountController = TextEditingController( + text: _formatAmountInput(remaining), + ); + final allocation = await showDialog<_PaymentAllocation>( + context: context, + builder: (dialogContext) => StatefulBuilder( + builder: (context, setDialogState) => AlertDialog( + title: Text('Adicionar ${category.label}'), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (options.length > 1) + DropdownButtonFormField( + value: selectedMethod, + decoration: const InputDecoration(labelText: 'Condição'), + items: options + .map( + (method) => DropdownMenuItem( + value: method, + child: Text( + method.name, + overflow: TextOverflow.ellipsis, + ), + ), + ) + .toList(growable: false), + onChanged: (method) { + if (method != null) { + setDialogState(() => selectedMethod = method); + } + }, + ) + else + Text(selectedMethod.name), + const SizedBox(height: 12), + TextField( + controller: amountController, + autofocus: true, + keyboardType: + const TextInputType.numberWithOptions(decimal: true), + decoration: InputDecoration( + labelText: 'Valor desta parcela', + prefixText: 'R\$ ', + hintText: '0,00', + errorText: validationMessage, + ), + ), + const SizedBox(height: 8), + Text( + 'Saldo disponível: ${CurrencyFormatter.formatBrl(remaining)}'), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Cancelar'), + ), + FilledButton( + onPressed: () { + final amount = _parseAmountMinorUnits(amountController.text); + if (amount == null || amount <= 0) { + setDialogState(() { + validationMessage = 'Informe um valor válido.'; + }); + return; + } + if (amount > remaining) { + setDialogState(() { + validationMessage = 'O valor excede o saldo disponível.'; + }); + return; + } + Navigator.of(dialogContext).pop( + _PaymentAllocation( + method: selectedMethod, + amountMinor: amount, + ), + ); + }, + child: const Text('Adicionar'), + ), + ], + ), + ), + ); + amountController.dispose(); + + if (mounted && allocation != null) { + setState(() => _allocations.add(allocation)); + } + } + + static String _formatAmountInput(int amountMinor) { + final whole = amountMinor ~/ 100; + final cents = (amountMinor % 100).toString().padLeft(2, '0'); + return '$whole,$cents'; + } + + static int? _parseAmountMinorUnits(String input) { + var value = input.trim().replaceAll('R\$', '').replaceAll(' ', ''); + if (value.isEmpty) return null; + + final commaIndex = value.lastIndexOf(','); + final dotIndex = value.lastIndexOf('.'); + final decimalIndex = commaIndex > dotIndex ? commaIndex : dotIndex; + String whole; + String fraction; + if (decimalIndex < 0) { + whole = value; + fraction = ''; + } else { + whole = value.substring(0, decimalIndex).replaceAll(RegExp(r'[.,]'), ''); + fraction = value.substring(decimalIndex + 1); + if (fraction.length > 2 || fraction.isEmpty) return null; + } + if (whole.isEmpty) whole = '0'; + if (!RegExp(r'^\d+$').hasMatch(whole) || + (fraction.isNotEmpty && !RegExp(r'^\d+$').hasMatch(fraction))) { + return null; + } + final cents = fraction.isEmpty ? 0 : int.parse(fraction.padRight(2, '0')); + return int.parse(whole) * 100 + cents; + } + + Widget _buildPaymentCategories(int? total) { + return GridView.count( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + crossAxisCount: 2, + crossAxisSpacing: 10, + mainAxisSpacing: 10, + childAspectRatio: 1.55, + children: _PaymentCategory.values.map((category) { + final options = _methodsFor(category); + final colorScheme = Theme.of(context).colorScheme; + return FilledButton.tonal( + key: Key('payment-category-${category.name}'), + onPressed: + options.isEmpty || total == null || _allocatedMinorUnits >= total + ? null + : () => _addPayment(category, total), + style: FilledButton.styleFrom( + minimumSize: const Size.fromHeight(92), + padding: const EdgeInsets.all(8), + backgroundColor: colorScheme.surfaceVariant, + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(category.icon, size: 30), + const SizedBox(height: 6), + Text(category.label, textAlign: TextAlign.center), + ], + ), + ); + }).toList(growable: false), + ); + } + + Widget _buildAllocations(int? total) { + if (_allocations.isEmpty) return const SizedBox.shrink(); + + final cashReceived = _allocations + .where((allocation) => allocation.isCash) + .fold(0, (sum, allocation) => sum + allocation.amountMinor); + final awaitingTerminal = _allocations + .where((allocation) => !allocation.isCash) + .fold(0, (sum, allocation) => sum + allocation.amountMinor); + final remaining = total == null ? null : total - _allocatedMinorUnits; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(height: 16), + Text('Pagamentos lançados', + style: Theme.of(context).textTheme.titleMedium), + if (cashReceived > 0) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + 'Dinheiro recebido: ${CurrencyFormatter.formatBrl(cashReceived)}', + ), + ), + if (awaitingTerminal > 0) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + 'Aguardando API do POS: ' + '${CurrencyFormatter.formatBrl(awaitingTerminal)}', + ), + ), + if (remaining != null) + Padding( + padding: const EdgeInsets.only(top: 4, bottom: 4), + child: Text( + 'Saldo a distribuir: ${CurrencyFormatter.formatBrl(remaining)}', + style: Theme.of(context).textTheme.titleSmall, + ), + ), + ..._allocations.asMap().entries.map((entry) { + final index = entry.key; + final allocation = entry.value; + return Card( + child: ListTile( + title: Text(allocation.method.name), + subtitle: Text( + allocation.isCash ? 'Recebido' : 'Pendente de confirmação POS', + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(CurrencyFormatter.formatBrl(allocation.amountMinor)), + IconButton( + tooltip: 'Remover pagamento', + icon: const Icon(Icons.delete_outline), + onPressed: () => + setState(() => _allocations.removeAt(index)), + ), + ], + ), + ), + ); + }), + ], + ); + } + + @override + Widget build(BuildContext context) { + final items = widget.services.cartRepository.items; + final total = widget.services.cartRepository.totalMinorUnits; + return PopScope( + canPop: !_finalizing, + child: Stack( + fit: StackFit.expand, + children: [ + Scaffold( + appBar: AppBar(title: const Text('Pagamento')), + body: SafeArea( + child: Column( + children: [ + Expanded( + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + 'Total da venda (prévia)', + style: Theme.of(context).textTheme.bodyMedium, + ), + const SizedBox(height: 4), + Text( + total == null + ? 'Total indisponível' + : CurrencyFormatter.formatBrl(total), + style: Theme.of(context) + .textTheme + .headlineSmall + ?.copyWith(fontWeight: FontWeight.bold), + ), + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: Text( + _customer?.name ?? + 'Consumidor não identificado', + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: Theme.of(context) + .textTheme + .titleSmall, + ), + ), + TextButton.icon( + onPressed: _includeCustomer, + icon: const Icon(Icons.person_add_alt_1), + label: Text( + _customer == null + ? 'Incluir cliente' + : 'Alterar cliente', + ), + ), + ], + ), + if (_customer?.documentMasked.isNotEmpty == + true) + Align( + alignment: Alignment.centerLeft, + child: Text( + _customer!.documentMasked, + style: + Theme.of(context).textTheme.bodySmall, + ), + ), + ], + ), + ), + ), + const SizedBox(height: 12), + Text( + 'Formas de pagamento disponíveis', + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 8), + if (_loading) + const LoadingView(message: 'Carregando pagamentos...') + else if (_errorMessage != null) + ErrorView( + message: _errorMessage!, + onRetry: _loadPaymentMethods, + ) + else if (_methods.isEmpty) + const EmptyView( + title: 'Nenhuma forma de pagamento', + message: + 'O servidor não retornou formas disponíveis.', + icon: Icons.payments_outlined, + ) + else + _buildPaymentCategories(total), + _buildAllocations(total), + if (_checkoutError != null) + Padding( + padding: const EdgeInsets.only(top: 12), + child: Text( + _checkoutError!, + style: TextStyle( + color: Theme.of(context).colorScheme.error, + ), + ), + ), + if (_methods.isNotEmpty && + !_loading && + _errorMessage == null) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + 'Por enquanto, a finalização aceita somente dinheiro. ' + 'PIX e cartões aguardam confirmação da API do POS.', + style: Theme.of(context).textTheme.bodySmall, + textAlign: TextAlign.center, + ), + ), + ], + ), + ), + if (items.isEmpty) + Padding( + padding: const EdgeInsets.all(16), + child: AppButton( + label: 'Voltar para venda', + icon: Icons.storefront_outlined, + onPressed: () => Navigator.of(context).popUntil( + (route) => route.settings.name == AppRoutes.sale, + ), + ), + ) + else + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: AppButton( + label: + _finalizing ? 'Finalizando...' : 'Finalizar venda', + icon: Icons.check_circle_outline, + onPressed: _canFinalize(total) + ? () => _finalizeCashSale(total) + : null, + ), + ), + ], + ), + ), + ), + if (_finalizing) ...[ + const ModalBarrier( + dismissible: false, + color: Color(0x99000000), + ), + Center( + child: Card( + margin: const EdgeInsets.all(28), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 32, + vertical: 28, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox.square( + dimension: 52, + child: CircularProgressIndicator(strokeWidth: 5), + ), + const SizedBox(height: 20), + Text( + 'Finalizando a venda', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.titleLarge, + ), + const SizedBox(height: 8), + Text( + 'Aguardando o retorno do Odoo e da SEFAZ. ' + 'Não feche o aplicativo.', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyMedium, + ), + ], + ), + ), + ), + ), + ], + ], + ), + ); + } +} diff --git a/pdv/lib/features/payment/presentation/sale_complete_screen.dart b/pdv/lib/features/payment/presentation/sale_complete_screen.dart new file mode 100644 index 0000000..3a7fb1d --- /dev/null +++ b/pdv/lib/features/payment/presentation/sale_complete_screen.dart @@ -0,0 +1,189 @@ +import 'package:flutter/material.dart'; + +import '../../../app/app_services.dart'; +import '../../../app/router/app_router.dart'; +import '../../../domain/entities/sale_completion.dart'; +import '../../../core/widgets/app_button.dart'; + +class SaleCompleteScreen extends StatelessWidget { + const SaleCompleteScreen({ + required this.services, + required this.completion, + super.key, + }); + + final AppServices services; + final SaleCompletion completion; + + void _startNextSale(BuildContext context) { + services.cartRepository.clear(); + Navigator.of(context).popUntil( + (route) => route.settings.name == AppRoutes.sale, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Venda finalizada'), + automaticallyImplyLeading: false, + ), + body: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 520), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Icon( + Icons.check_circle, + size: 88, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(height: 16), + Text( + 'NFC-e gerada', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineSmall, + ), + const SizedBox(height: 20), + Card( + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + children: [ + _DocumentRow( + label: 'Pedido', + value: completion.orderNumber, + ), + const Divider(height: 24), + _DocumentRow( + label: 'Número NFC-e', + value: completion.invoiceNumber, + ), + const Divider(height: 24), + _DocumentRow( + label: 'Série', + value: completion.invoiceSeries, + ), + const Divider(height: 24), + _DocumentRow( + label: 'Estado da NFC-e', + value: _invoiceStateLabel( + completion.invoiceState, + completion.invoiceContingency, + ), + ), + ], + ), + ), + ), + if (completion.invoiceMessage.isNotEmpty) ...[ + const SizedBox(height: 12), + Card( + color: Theme.of(context).colorScheme.surface, + child: Padding( + padding: const EdgeInsets.all(16), + child: Text( + completion.invoiceMessage, + ), + ), + ), + ], + const SizedBox(height: 20), + AppButton( + label: 'Imprimir NFC-e', + icon: Icons.print_outlined, + onPressed: () => _showPrintNotConfigured(context), + ), + const SizedBox(height: 10), + AppButton( + label: 'Nova venda', + icon: Icons.storefront_outlined, + onPressed: () => _startNextSale(context), + ), + ], + ), + ), + ), + ), + ), + ); + } + + void _showPrintNotConfigured(BuildContext context) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Impressão indisponível'), + content: const Text( + 'A API/SDK da impressora do POS ainda não foi configurada.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Fechar'), + ), + ], + ), + ); + } + + String _invoiceStateLabel(String state, bool contingency) { + if (contingency) return 'Emitida em Contingência'; + switch (state) { + case '1': + return 'Rascunho'; + case '2': + return 'Validada'; + case '2E': + return 'Validada com erro'; + case '3': + return 'Faturada/autorizada'; + case 'C': + return 'Cancelada'; + case 'D': + return 'Denegada'; + case 'EP': + return 'Em processamento'; + case 'I': + return 'Inutilizada'; + case 'P': + return 'Pendente'; + default: + return state.isEmpty ? 'Não informado' : state; + } + } +} + +class _DocumentRow extends StatelessWidget { + const _DocumentRow({required this.label, required this.value}); + + final String label; + final String value; + + @override + Widget build(BuildContext context) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(label), + const SizedBox(width: 16), + Flexible( + child: Text( + value, + textAlign: TextAlign.end, + style: Theme.of(context) + .textTheme + .titleMedium + ?.copyWith(fontWeight: FontWeight.bold), + ), + ), + ], + ); + } +} diff --git a/pdv/lib/features/sale/presentation/sale_screen.dart b/pdv/lib/features/sale/presentation/sale_screen.dart new file mode 100644 index 0000000..41e00af --- /dev/null +++ b/pdv/lib/features/sale/presentation/sale_screen.dart @@ -0,0 +1,597 @@ +import 'dart:convert'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart'; + +import '../../../app/app_services.dart'; +import '../../../app/router/app_router.dart'; +import '../../../core/utils/currency_formatter.dart'; +import '../../../core/widgets/empty_view.dart'; +import '../../../core/widgets/error_view.dart'; +import '../../../core/widgets/loading_view.dart'; +import '../../../domain/entities/department.dart'; +import '../../../domain/entities/product.dart'; +import '../../../domain/entities/sale_view_mode.dart'; +import '../../../domain/repositories/catalog_repository.dart'; + +class SaleScreen extends StatefulWidget { + const SaleScreen({required this.services, super.key}); + + final AppServices services; + + @override + State createState() => _SaleScreenState(); +} + +class _SaleScreenState extends State { + final Map> _productsByDepartment = {}; + List _departments = []; + int? _selectedDepartmentId; + bool _loadingDepartments = true; + bool _loadingProducts = false; + bool _showKanban = true; + bool _scanningBarcode = false; + String? _departmentError; + String? _productError; + int _productRequest = 0; + + @override + void initState() { + super.initState(); + _initialize(); + } + + Future _initialize() async { + final userId = widget.services.authRepository.currentSession?.userId; + if (userId != null) { + try { + final viewMode = await widget.services.saleViewPreferenceRepository + .loadForUser(userId); + if (mounted) { + setState(() => _showKanban = viewMode == SaleViewMode.kanban); + } + } catch (_) { + // Use Kanban as the default if preference storage is unavailable. + } + } + if (mounted) await _loadDepartments(); + } + + Future _setViewMode(bool showKanban) async { + setState(() => _showKanban = showKanban); + final userId = widget.services.authRepository.currentSession?.userId; + if (userId == null) return; + try { + await widget.services.saleViewPreferenceRepository.saveForUser( + userId, + showKanban ? SaleViewMode.kanban : SaleViewMode.list, + ); + } catch (_) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Não foi possível salvar a visualização.')), + ); + } + } + } + + Future _loadDepartments() async { + setState(() { + _loadingDepartments = true; + _departmentError = null; + }); + try { + final departments = + await widget.services.catalogRepository.fetchDepartments(); + if (!mounted) return; + setState(() { + _departments = departments; + _selectedDepartmentId = + departments.isEmpty ? null : departments.first.id; + _loadingDepartments = false; + }); + if (departments.isNotEmpty) { + await _selectDepartment(departments.first); + } + } on CatalogException catch (error) { + if (mounted) { + setState(() { + _departmentError = error.message; + _loadingDepartments = false; + }); + } + } catch (_) { + if (mounted) { + setState(() { + _departmentError = 'Não foi possível carregar os departamentos.'; + _loadingDepartments = false; + }); + } + } + } + + Future _selectDepartment(Department department) async { + setState(() { + _selectedDepartmentId = department.id; + _productError = null; + _loadingProducts = !_productsByDepartment.containsKey(department.id); + }); + if (_productsByDepartment.containsKey(department.id)) return; + + final requestId = ++_productRequest; + try { + final products = await widget.services.catalogRepository + .fetchProductsByDepartment(department.id); + if (!mounted || requestId != _productRequest) return; + setState(() { + _productsByDepartment[department.id] = products; + _loadingProducts = false; + }); + } on CatalogException catch (error) { + if (mounted && requestId == _productRequest) { + setState(() { + _productError = error.message; + _loadingProducts = false; + }); + } + } catch (_) { + if (mounted && requestId == _productRequest) { + setState(() { + _productError = 'Não foi possível carregar os produtos.'; + _loadingProducts = false; + }); + } + } + } + + Future _retryProducts() async { + final selectedId = _selectedDepartmentId; + if (selectedId == null) return; + _productsByDepartment.remove(selectedId); + final department = _departments.firstWhere((item) => item.id == selectedId); + await _selectDepartment(department); + } + + void _addProduct(Product product) { + widget.services.cartRepository.addProduct(product); + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text('${product.name} adicionado.'))); + } + + Future _scanProductBarcode() async { + if (_scanningBarcode) return; + setState(() => _scanningBarcode = true); + try { + final barcode = await FlutterBarcodeScanner.scanBarcode( + '#ff6666', + 'Cancelar', + true, + ScanMode.BARCODE, + ); + if (!mounted || barcode == '-1' || barcode.trim().isEmpty) return; + + final product = await widget.services.catalogRepository + .fetchProductByBarcode(barcode.trim()); + if (!mounted) return; + if (product == null) { + await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: const Text('Produto não encontrado'), + content: Text('O código "$barcode" não foi encontrado.'), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Ok'), + ), + ], + ), + ); + return; + } + _addProduct(product); + } on PlatformException { + if (mounted) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar( + const SnackBar(content: Text('Não foi possível abrir a câmera.')), + ); + } + } on CatalogException catch (error) { + if (mounted) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(error.message))); + } + } catch (_) { + if (mounted) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar( + const SnackBar( + content: Text('Não foi possível consultar o código lido.'), + ), + ); + } + } finally { + if (mounted) setState(() => _scanningBarcode = false); + } + } + + String get _selectedDepartmentName { + for (final department in _departments) { + if (department.id == _selectedDepartmentId) return department.name; + } + return ''; + } + + Widget _productImage( + Product product, { + double? width, + double? height, + BoxFit fit = BoxFit.cover, + }) { + final encodedImage = product.imageBase64; + if (encodedImage == null) return _imagePlaceholder(width, height); + try { + return Image.memory( + base64Decode(encodedImage), + width: width, + height: height, + fit: fit, + errorBuilder: (_, __, ___) => _imagePlaceholder(width, height), + ); + } on FormatException { + return _imagePlaceholder(width, height); + } + } + + Widget _imagePlaceholder(double? width, double? height) { + return Container( + width: width, + height: height, + color: Theme.of(context).colorScheme.surfaceVariant, + alignment: Alignment.center, + child: const Icon(Icons.image_outlined, size: 36), + ); + } + + Widget _buildProductCard(Product product, {required bool grid}) { + if (grid) { + return Card( + clipBehavior: Clip.antiAlias, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: ColoredBox( + color: Theme.of(context).colorScheme.surfaceVariant, + child: _productImage(product, fit: BoxFit.contain), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(6, 6, 6, 2), + child: Text( + product.name, + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 6), + child: Text( + product.code, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(4, 2, 4, 0), + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + CurrencyFormatter.formatBrl(product.priceMinorUnits), + style: Theme.of(context) + .textTheme + .labelLarge + ?.copyWith(fontWeight: FontWeight.bold), + ), + ), + ), + Align( + alignment: Alignment.center, + child: IconButton.filledTonal( + constraints: + const BoxConstraints.tightFor(width: 38, height: 38), + padding: EdgeInsets.zero, + tooltip: 'Adicionar ${product.name}', + onPressed: () => _addProduct(product), + icon: const Icon(Icons.add_shopping_cart, size: 18), + ), + ), + ], + ), + ); + } + + return Card( + clipBehavior: Clip.antiAlias, + child: ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + leading: SizedBox.square( + dimension: 64, + child: ClipRRect( + borderRadius: BorderRadius.circular(8), + child: _productImage(product), + ), + ), + title: Text( + product.name, + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall, + ), + subtitle: Text( + 'Código ${product.code} · ' + '${CurrencyFormatter.formatBrl(product.priceMinorUnits)}', + style: Theme.of(context) + .textTheme + .bodySmall + ?.copyWith(fontWeight: FontWeight.bold), + ), + trailing: IconButton.filledTonal( + tooltip: 'Adicionar ${product.name}', + onPressed: () => _addProduct(product), + icon: const Icon(Icons.add_shopping_cart), + ), + ), + ); + } + + Widget _buildProducts() { + if (_loadingProducts) { + return const LoadingView(message: 'Carregando produtos...'); + } + if (_productError != null) { + return ErrorView(message: _productError!, onRetry: _retryProducts); + } + final products = _productsByDepartment[_selectedDepartmentId] ?? []; + if (products.isEmpty) { + return const EmptyView( + title: 'Nenhum produto', + message: 'Não há produtos neste departamento.', + icon: Icons.inventory_2_outlined, + ); + } + if (!_showKanban) { + return ListView.builder( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), + itemCount: products.length, + itemBuilder: (_, index) => + _buildProductCard(products[index], grid: false), + ); + } + + return LayoutBuilder( + builder: (context, constraints) { + final tileWidth = (constraints.maxWidth - 44) / 3; + // Reserve at least 64 px for the image, matching the list thumbnail. + final tileHeight = math.max(196.0, tileWidth / 0.9); + return GridView.builder( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 3, + crossAxisSpacing: 10, + mainAxisSpacing: 10, + childAspectRatio: tileWidth / tileHeight, + ), + itemCount: products.length, + itemBuilder: (_, index) => + _buildProductCard(products[index], grid: true), + ); + }, + ); + } + + Widget _buildCartBar() { + return AnimatedBuilder( + animation: widget.services.cartRepository, + builder: (context, _) { + final itemCount = widget.services.cartRepository.itemCount; + final totalMinorUnits = widget.services.cartRepository.totalMinorUnits; + return Material( + elevation: 4, + color: Theme.of(context).colorScheme.surface, + child: SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.all(12), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'Total do carrinho', + style: Theme.of(context).textTheme.bodySmall, + ), + Text( + totalMinorUnits == null + ? 'Total indisponível' + : CurrencyFormatter.formatBrl(totalMinorUnits), + style: Theme.of(context) + .textTheme + .titleMedium + ?.copyWith(fontWeight: FontWeight.bold), + ), + ], + ), + ), + SizedBox.square( + dimension: 56, + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned.fill( + child: IconButton.filledTonal( + tooltip: 'Carrinho', + onPressed: itemCount == 0 + ? null + : () => Navigator.of(context) + .pushNamed(AppRoutes.cart), + icon: const Icon(Icons.shopping_cart_outlined), + ), + ), + if (itemCount > 0) + Positioned( + top: -2, + right: -2, + child: Container( + constraints: const BoxConstraints( + minWidth: 20, + minHeight: 20, + ), + padding: + const EdgeInsets.symmetric(horizontal: 5), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.error, + borderRadius: BorderRadius.circular(10), + ), + alignment: Alignment.center, + child: Text( + itemCount > 99 ? '99+' : '$itemCount', + style: TextStyle( + color: Theme.of(context).colorScheme.onError, + fontSize: 11, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), + ), + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Venda'), + actions: [ + IconButton( + key: const Key('refresh-products-button'), + tooltip: 'Atualizar produtos', + onPressed: _loadingProducts || _selectedDepartmentId == null + ? null + : _retryProducts, + icon: const Icon(Icons.refresh), + ), + ], + ), + body: SafeArea( + child: Column( + children: [ + if (_loadingDepartments) + const Expanded( + child: LoadingView(message: 'Carregando departamentos...'), + ) + else if (_departmentError != null) + Expanded( + child: ErrorView( + message: _departmentError!, + onRetry: _loadDepartments, + ), + ) + else if (_departments.isEmpty) + const Expanded( + child: EmptyView( + title: 'Nenhum departamento', + message: 'O servidor não retornou departamentos para venda.', + icon: Icons.category_outlined, + ), + ) + else ...[ + SizedBox( + height: 58, + child: ListView.separated( + padding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + scrollDirection: Axis.horizontal, + itemCount: _departments.length, + separatorBuilder: (_, __) => const SizedBox(width: 8), + itemBuilder: (context, index) { + final department = _departments[index]; + return ChoiceChip( + label: Text(department.name), + selected: department.id == _selectedDepartmentId, + onSelected: (_) => _selectDepartment(department), + ); + }, + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 8, 8), + child: Row( + children: [ + Expanded( + child: Text( + _selectedDepartmentName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.titleMedium, + ), + ), + IconButton.filledTonal( + tooltip: 'Ler código de barras', + onPressed: _scanningBarcode ? null : _scanProductBarcode, + icon: _scanningBarcode + ? SizedBox.square( + dimension: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Theme.of(context) + .colorScheme + .onSecondaryContainer, + ), + ) + : const Icon(Icons.camera_alt_outlined), + ), + const SizedBox(width: 20), + IconButton( + tooltip: _showKanban + ? 'Visualizar em lista' + : 'Visualizar em Kanban', + onPressed: () => _setViewMode(!_showKanban), + icon: Icon( + _showKanban ? Icons.view_list : Icons.grid_view, + ), + ), + ], + ), + ), + Expanded(child: _buildProducts()), + ], + ], + ), + ), + bottomNavigationBar: _buildCartBar(), + ); + } +} diff --git a/pdv/lib/features/sales_history/presentation/sales_history_screen.dart b/pdv/lib/features/sales_history/presentation/sales_history_screen.dart new file mode 100644 index 0000000..8f328be --- /dev/null +++ b/pdv/lib/features/sales_history/presentation/sales_history_screen.dart @@ -0,0 +1,255 @@ +import 'package:flutter/material.dart'; + +import '../../../app/app_services.dart'; +import '../../../core/utils/currency_formatter.dart'; +import '../../../domain/entities/historical_sale.dart'; +import '../../../domain/repositories/sales_history_repository.dart'; + +class SalesHistoryScreen extends StatefulWidget { + const SalesHistoryScreen({required this.services, super.key}); + + final AppServices services; + + @override + State createState() => _SalesHistoryScreenState(); +} + +class _SalesHistoryScreenState extends State { + late Future> _salesFuture; + + @override + void initState() { + super.initState(); + _salesFuture = widget.services.salesHistoryRepository.fetchSales(); + } + + Future _reload() async { + final future = widget.services.salesHistoryRepository.fetchSales(); + setState(() => _salesFuture = future); + try { + await future; + } catch (_) { + // FutureBuilder displays the error while RefreshIndicator is dismissed. + } + } + + String _formatDate(String value) { + final parts = value.split('-'); + if (parts.length != 3) return value; + return '${parts[2]}/${parts[1]}/${parts[0]}'; + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Histórico de vendas')), + body: SafeArea( + child: FutureBuilder>( + future: _salesFuture, + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Center(child: CircularProgressIndicator()); + } + if (snapshot.hasError) { + final error = snapshot.error; + final message = error is SalesHistoryException + ? error.message + : 'Não foi possível carregar o histórico de vendas.'; + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.error_outline, size: 48), + const SizedBox(height: 12), + Text(message, textAlign: TextAlign.center), + const SizedBox(height: 16), + FilledButton.icon( + onPressed: _reload, + icon: const Icon(Icons.refresh), + label: const Text('Tentar novamente'), + ), + ], + ), + ), + ); + } + + final sales = snapshot.data ?? const []; + if (sales.isEmpty) { + return RefreshIndicator( + onRefresh: _reload, + child: ListView( + physics: const AlwaysScrollableScrollPhysics(), + children: const [ + SizedBox(height: 120), + Icon(Icons.receipt_long_outlined, size: 56), + SizedBox(height: 16), + Center(child: Text('Nenhuma venda encontrada.')), + SizedBox(height: 24), + ], + ), + ); + } + + return RefreshIndicator( + onRefresh: _reload, + child: ListView.separated( + physics: const AlwaysScrollableScrollPhysics(), + padding: const EdgeInsets.all(16), + itemCount: sales.length, + separatorBuilder: (_, __) => const SizedBox(height: 8), + itemBuilder: (context, index) => _SaleCard( + sale: sales[index], + formatDate: _formatDate, + onReprint: _confirmReprint, + ), + ), + ); + }, + ), + ), + ); + } + + Future _confirmReprint(HistoricalSale sale) async { + final shouldReprint = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: const Text('Reimprimir NFC-e?'), + content: Text( + 'Deseja reimprimir a nota do pedido ${sale.orderNumber}?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: const Text('Cancelar'), + ), + FilledButton.icon( + onPressed: () => Navigator.of(dialogContext).pop(true), + icon: const Icon(Icons.print_outlined), + label: const Text('Reimprimir'), + ), + ], + ), + ); + if (shouldReprint != true || !mounted) return; + await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: const Text('Impressão indisponível'), + content: const Text( + 'A impressão da NFC-e ainda depende da integração com a API/SDK ' + 'da impressora do POS.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Fechar'), + ), + ], + ), + ); + } +} + +class _SaleCard extends StatelessWidget { + const _SaleCard({ + required this.sale, + required this.formatDate, + required this.onReprint, + }); + + final HistoricalSale sale; + final String Function(String) formatDate; + final ValueChanged onReprint; + + Color _backgroundColor() => switch (sale.state) { + 'V' => const Color(0xFFE8F5E9), + 'F' => const Color(0xFFFFEBEE), + _ => Colors.white, + }; + + Color _stateColor() => switch (sale.state) { + 'V' => const Color(0xFF2E7D32), + 'F' => const Color(0xFFC62828), + _ => Colors.black87, + }; + + String _stateLabel() => switch (sale.state) { + 'V' => 'Validado', + 'F' => 'Faturado', + _ => sale.state, + }; + + @override + Widget build(BuildContext context) { + return Card( + color: _backgroundColor(), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: sale.state == 'F' ? () => onReprint(sale) : null, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.receipt_long_outlined), + const SizedBox(width: 10), + Expanded( + child: Text( + 'Pedido ${sale.orderNumber}', + style: Theme.of(context).textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ), + Text( + CurrencyFormatter.formatBrl(sale.totalMinorUnits), + style: Theme.of(context).textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ], + ), + const SizedBox(height: 8), + Align( + alignment: Alignment.centerRight, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _stateLabel(), + style: TextStyle( + color: _stateColor(), + fontWeight: FontWeight.w700, + ), + ), + if (sale.state == 'F') ...[ + const SizedBox(width: 6), + Icon(Icons.print_outlined, + size: 18, color: _stateColor()), + ], + ], + ), + ), + const SizedBox(height: 10), + Text('Emissão: ${formatDate(sale.issueDate)}'), + if (sale.customerName.trim().isNotEmpty) ...[ + const SizedBox(height: 4), + Text( + 'Cliente: ${sale.customerName}', + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ], + ], + ), + ), + ), + ); + } +} diff --git a/pdv/lib/features/settings/presentation/settings_screen.dart b/pdv/lib/features/settings/presentation/settings_screen.dart new file mode 100644 index 0000000..78983a3 --- /dev/null +++ b/pdv/lib/features/settings/presentation/settings_screen.dart @@ -0,0 +1,236 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../app/app_services.dart'; +import '../../../core/config/server_url_validator.dart'; +import '../../../core/widgets/app_button.dart'; +import '../../../core/widgets/error_view.dart'; +import '../../../core/widgets/loading_view.dart'; +import '../../../domain/entities/app_settings.dart'; + +class SettingsScreen extends StatefulWidget { + const SettingsScreen({required this.services, super.key}); + + final AppServices services; + + @override + State createState() => _SettingsScreenState(); +} + +class _SettingsScreenState extends State { + final _formKey = GlobalKey(); + final _serverUrlController = TextEditingController(); + final _identifierController = TextEditingController(); + bool _loading = true; + bool _saving = false; + bool _testing = false; + Object? _loadError; + + @override + void initState() { + super.initState(); + _loadSettings(); + } + + @override + void dispose() { + _serverUrlController.dispose(); + _identifierController.dispose(); + super.dispose(); + } + + Future _loadSettings() async { + setState(() { + _loading = true; + _loadError = null; + }); + try { + final settings = await widget.services.settingsRepository.load(); + if (!mounted) return; + _serverUrlController.text = settings?.serverUrl ?? ''; + _identifierController.text = settings?.companyIdentifier ?? ''; + setState(() => _loading = false); + } catch (error) { + if (mounted) { + setState(() { + _loadError = error; + _loading = false; + }); + } + } + } + + String? _validateServerUrl(String? value) => + ServerUrlValidator.validate(value ?? ''); + + String? _validateIdentifier(String? value) { + final identifier = value?.trim() ?? ''; + if (identifier.isEmpty) return 'Informe o identificador da empresa.'; + if (identifier.length > 14 || + !RegExp(r'^[a-zA-Z0-9]+$').hasMatch(identifier)) { + return 'Use até 14 letras ou números.'; + } + return null; + } + + AppSettings _formSettings() => AppSettings( + serverUrl: _serverUrlController.text.trim(), + companyIdentifier: _identifierController.text.trim(), + ); + + Future _testConnection() async { + if (_testing || !_formKey.currentState!.validate()) return; + setState(() => _testing = true); + try { + final result = await widget.services.connectionTester.test( + Uri.parse(_serverUrlController.text.trim()), + ); + if (mounted) _showMessage(result.message); + } catch (_) { + if (mounted) { + _showMessage('Não foi possível testar a conexão. Tente novamente.'); + } + } finally { + if (mounted) setState(() => _testing = false); + } + } + + Future _save() async { + if (_saving || !_formKey.currentState!.validate()) return; + setState(() => _saving = true); + try { + final settings = _formSettings(); + final previous = await widget.services.settingsRepository.load(); + if (previous != settings) { + await widget.services.authRepository.logout(); + } + await widget.services.settingsRepository.save(settings); + if (mounted) { + _showMessage('Configuração salva.'); + Navigator.of(context).pop(); + } + } catch (_) { + if (mounted) _showMessage('Não foi possível salvar a configuração.'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + void _showMessage(String message) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(message))); + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return const Scaffold( + body: LoadingView(message: 'Carregando configuração...')); + } + if (_loadError != null) { + return Scaffold( + appBar: AppBar( + automaticallyImplyLeading: false, + title: const Text('Configuração'), + ), + body: ErrorView( + message: 'Não foi possível carregar a configuração.', + onRetry: _loadSettings, + ), + ); + } + + final busy = _saving || _testing; + return Scaffold( + appBar: AppBar( + automaticallyImplyLeading: false, + title: const Text('Configuração'), + ), + body: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 520), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(height: 24), + TextFormField( + key: const Key('settings-server-url'), + controller: _serverUrlController, + enabled: !busy, + keyboardType: TextInputType.url, + textInputAction: TextInputAction.next, + autocorrect: false, + decoration: const InputDecoration( + labelText: 'Servidor (URL)', + hintText: 'https://odoo.exemplo.com', + helperText: + 'Aceita HTTP e HTTPS. HTTP não criptografa os dados.', + prefixIcon: Icon(Icons.language), + ), + validator: _validateServerUrl, + ), + const SizedBox(height: 16), + TextFormField( + key: const Key('settings-company-identifier'), + controller: _identifierController, + enabled: !busy, + maxLength: 14, + textCapitalization: TextCapitalization.characters, + textInputAction: TextInputAction.done, + inputFormatters: [ + FilteringTextInputFormatter.allow( + RegExp('[a-zA-Z0-9]')), + LengthLimitingTextInputFormatter(14), + ], + decoration: const InputDecoration( + labelText: 'CNPJ', + prefixIcon: Icon(Icons.business_outlined), + ), + validator: _validateIdentifier, + ), + const SizedBox(height: 8), + OutlinedButton.icon( + key: const Key('test-connection-button'), + onPressed: busy ? null : _testConnection, + icon: _testing + ? const SizedBox.square( + dimension: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.wifi_tethering), + label: const Text('Testar conexão'), + style: OutlinedButton.styleFrom( + minimumSize: const Size.fromHeight(52), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + ), + const SizedBox(height: 12), + AppButton( + label: _saving ? 'Salvando...' : 'Salvar', + icon: Icons.save_outlined, + onPressed: busy ? null : _save, + ), + const SizedBox(height: 8), + TextButton( + onPressed: + busy ? null : () => Navigator.of(context).pop(), + child: const Text('Cancelar'), + ), + ], + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/pdv/lib/features/shared/presentation/placeholder_screen.dart b/pdv/lib/features/shared/presentation/placeholder_screen.dart new file mode 100644 index 0000000..924d23a --- /dev/null +++ b/pdv/lib/features/shared/presentation/placeholder_screen.dart @@ -0,0 +1,22 @@ +import 'package:flutter/material.dart'; + +import '../../../core/widgets/empty_view.dart'; + +class PlaceholderScreen extends StatelessWidget { + const PlaceholderScreen({ + required this.title, + required this.message, + super.key, + }); + + final String title; + final String message; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: Text(title)), + body: EmptyView(title: title, message: message), + ); + } +} diff --git a/pdv/lib/main.dart b/pdv/lib/main.dart new file mode 100644 index 0000000..b125fda --- /dev/null +++ b/pdv/lib/main.dart @@ -0,0 +1,7 @@ +import 'package:flutter/material.dart'; + +import 'app/app.dart'; + +void main() { + runApp(const PdvApp()); +} diff --git a/pdv/linux/.gitignore b/pdv/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/pdv/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/pdv/linux/CMakeLists.txt b/pdv/linux/CMakeLists.txt new file mode 100644 index 0000000..7fd50b7 --- /dev/null +++ b/pdv/linux/CMakeLists.txt @@ -0,0 +1,145 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.10) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "pdv") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.pdv") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Define the application target. To change its name, change BINARY_NAME above, +# not the value here, or `flutter run` will no longer work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/pdv/linux/flutter/CMakeLists.txt b/pdv/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/pdv/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/pdv/linux/flutter/generated_plugin_registrant.cc b/pdv/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..d0e7f79 --- /dev/null +++ b/pdv/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin"); + flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar); +} diff --git a/pdv/linux/flutter/generated_plugin_registrant.h b/pdv/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/pdv/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/pdv/linux/flutter/generated_plugins.cmake b/pdv/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..b29e9ba --- /dev/null +++ b/pdv/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_secure_storage_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/pdv/linux/main.cc b/pdv/linux/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/pdv/linux/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/pdv/linux/my_application.cc b/pdv/linux/my_application.cc new file mode 100644 index 0000000..33e0243 --- /dev/null +++ b/pdv/linux/my_application.cc @@ -0,0 +1,104 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "pdv"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "pdv"); + } + + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/pdv/linux/my_application.h b/pdv/linux/my_application.h new file mode 100644 index 0000000..72271d5 --- /dev/null +++ b/pdv/linux/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/pdv/macos/.gitignore b/pdv/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/pdv/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/pdv/macos/Flutter/Flutter-Debug.xcconfig b/pdv/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/pdv/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/pdv/macos/Flutter/Flutter-Release.xcconfig b/pdv/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/pdv/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/pdv/macos/Flutter/GeneratedPluginRegistrant.swift b/pdv/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..6e1a5a8 --- /dev/null +++ b/pdv/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,20 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import device_info_plus +import flutter_secure_storage_macos +import package_info_plus +import path_provider_foundation +import shared_preferences_foundation + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) + FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin")) + FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) +} diff --git a/pdv/macos/Runner.xcodeproj/project.pbxproj b/pdv/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..fc46d70 --- /dev/null +++ b/pdv/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,695 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* pdv.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "pdv.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* pdv.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* pdv.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1430; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.pdv.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/pdv.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/pdv"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.pdv.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/pdv.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/pdv"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.pdv.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/pdv.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/pdv"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/pdv/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/pdv/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/pdv/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/pdv/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/pdv/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..dbf029f --- /dev/null +++ b/pdv/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pdv/macos/Runner.xcworkspace/contents.xcworkspacedata b/pdv/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/pdv/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/pdv/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/pdv/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/pdv/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/pdv/macos/Runner/AppDelegate.swift b/pdv/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..d53ef64 --- /dev/null +++ b/pdv/macos/Runner/AppDelegate.swift @@ -0,0 +1,9 @@ +import Cocoa +import FlutterMacOS + +@NSApplicationMain +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } +} diff --git a/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/pdv/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/pdv/macos/Runner/Base.lproj/MainMenu.xib b/pdv/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/pdv/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pdv/macos/Runner/Configs/AppInfo.xcconfig b/pdv/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..92db53c --- /dev/null +++ b/pdv/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = pdv + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.pdv + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/pdv/macos/Runner/Configs/Debug.xcconfig b/pdv/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/pdv/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/pdv/macos/Runner/Configs/Release.xcconfig b/pdv/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/pdv/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/pdv/macos/Runner/Configs/Warnings.xcconfig b/pdv/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/pdv/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/pdv/macos/Runner/DebugProfile.entitlements b/pdv/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/pdv/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/pdv/macos/Runner/Info.plist b/pdv/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/pdv/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/pdv/macos/Runner/MainFlutterWindow.swift b/pdv/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/pdv/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/pdv/macos/Runner/Release.entitlements b/pdv/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/pdv/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/pdv/macos/RunnerTests/RunnerTests.swift b/pdv/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..5418c9f --- /dev/null +++ b/pdv/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import FlutterMacOS +import Cocoa +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pdv/pubspec.lock b/pdv/pubspec.lock new file mode 100644 index 0000000..646bef1 --- /dev/null +++ b/pdv/pubspec.lock @@ -0,0 +1,482 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + characters: + dependency: transitive + description: + name: characters + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + clock: + dependency: transitive + description: + name: clock + sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf + url: "https://pub.dev" + source: hosted + version: "1.1.1" + collection: + dependency: transitive + description: + name: collection + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + url: "https://pub.dev" + source: hosted + version: "1.18.0" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + device_info_plus: + dependency: "direct main" + description: + name: device_info_plus + sha256: "77f757b789ff68e4eaf9c56d1752309bd9f7ad557cb105b938a7f8eb89e59110" + url: "https://pub.dev" + source: hosted + version: "9.1.2" + device_info_plus_platform_interface: + dependency: transitive + description: + name: device_info_plus_platform_interface + sha256: "0b04e02b30791224b31969eb1b50d723498f402971bff3630bca2ba839bd1ed2" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + ffi: + dependency: transitive + description: + name: ffi + sha256: "7bf0adc28a23d395f19f3f1eb21dd7cfd1dd9f8e1c50051c069122e6853bc878" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_barcode_scanner: + dependency: "direct main" + description: + name: flutter_barcode_scanner + sha256: a4ba37daf9933f451a5e812c753ddd045d6354e4a3280342d895b07fecaab3fa + url: "https://pub.dev" + source: hosted + version: "2.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04 + url: "https://pub.dev" + source: hosted + version: "2.0.3" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "8cf40eebf5dec866a6d1956ad7b4f7016e6c0cc69847ab946833b7d43743809f" + url: "https://pub.dev" + source: hosted + version: "2.0.19" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: "9cad52d75ebc511adfae3d447d5d13da15a55a92c9410e50f67335b6d21d16ea" + url: "https://pub.dev" + source: hosted + version: "9.2.4" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: be76c1d24a97d0b98f8b54bce6b481a380a6590df992d0098f868ad54dc8f688 + url: "https://pub.dev" + source: hosted + version: "1.2.3" + flutter_secure_storage_macos: + dependency: transitive + description: + name: flutter_secure_storage_macos + sha256: "6c0a2795a2d1de26ae202a0d78527d163f4acbb11cde4c75c670f3a0fc064247" + url: "https://pub.dev" + source: hosted + version: "3.1.3" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: cf91ad32ce5adef6fba4d736a542baca9daf3beac4db2d04be350b87f69ac4a8 + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: f4ebff989b4f07b2656fb16b47852c0aab9fed9b4ec1c70103368337bc1886a9 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: b20b07cb5ed4ed74fc567b78a72936203f587eba460af1df11281c9326cd3709 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + http: + dependency: "direct main" + description: + name: http + sha256: a2bbf9d017fcced29139daa8ed2bba4ece450ab222871df93ca9eec6f80c34ba + url: "https://pub.dev" + source: hosted + version: "1.2.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + js: + dependency: transitive + description: + name: js + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" + lints: + dependency: transitive + description: + name: lints + sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + matcher: + dependency: transitive + description: + name: matcher + sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" + url: "https://pub.dev" + source: hosted + version: "0.12.16" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41" + url: "https://pub.dev" + source: hosted + version: "0.5.0" + meta: + dependency: transitive + description: + name: meta + sha256: a6e590c838b18133bb482a2745ad77c5bb7715fb0451209e1a7567d416678b8e + url: "https://pub.dev" + source: hosted + version: "1.10.0" + package_info_plus: + dependency: "direct main" + description: + name: package_info_plus + sha256: "7e76fad405b3e4016cd39d08f455a4eb5199723cf594cd1b8916d47140d93017" + url: "https://pub.dev" + source: hosted + version: "4.2.0" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: "9bc8ba46813a4cc42c66ab781470711781940780fd8beddd0c3da62506d3a6c6" + url: "https://pub.dev" + source: hosted + version: "2.0.1" + path: + dependency: transitive + description: + name: path + sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" + url: "https://pub.dev" + source: hosted + version: "1.8.3" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: fec0d61223fba3154d87759e3cc27fe2c8dc498f6386c6d6fc80d1afdd1bf378 + url: "https://pub.dev" + source: hosted + version: "2.1.4" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: a248d8146ee5983446bf03ed5ea8f6533129a12b11f12057ad1b4a67a2b3b41d + url: "https://pub.dev" + source: hosted + version: "2.2.4" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "5a7999be66e000916500be4f15a3633ebceb8302719b47b9cc49ce924125350f" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: d3bbe5553a986e83980916ded2f0b435ef2e1893dfaa29d5a7a790d0eca12180 + url: "https://pub.dev" + source: hosted + version: "2.2.3" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "1ee8bf911094a1b592de7ab29add6f826a7331fb854273d55918693d5364a1f2" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "7708d83064f38060c7b39db12aefe449cb8cdc031d6062280087bc4cdb988f5c" + url: "https://pub.dev" + source: hosted + version: "2.3.5" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "2ba0510d3017f91655b7543e9ee46d48619de2a2af38e5c790423f7007c7ccc1" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: "7b15ffb9387ea3e237bb7a66b8a23d2147663d391cafc5c8f37b2e7b4bde5d21" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "398084b47b7f92110683cac45c6dc4aae853db47e470e5ddcd52cab7f7196ab2" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_span: + dependency: transitive + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test_api: + dependency: transitive + description: + name: test_api + sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + url: "https://pub.dev" + source: hosted + version: "0.6.1" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c + url: "https://pub.dev" + source: hosted + version: "1.3.2" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + web: + dependency: transitive + description: + name: web + sha256: afe077240a270dcfd2aafe77602b4113645af95d0ad31128cc02bce5ac5d5152 + url: "https://pub.dev" + source: hosted + version: "0.3.0" + win32: + dependency: transitive + description: + name: win32 + sha256: "464f5674532865248444b4c3daca12bd9bf2d7c47f759ce2617986e7229494a8" + url: "https://pub.dev" + source: hosted + version: "5.2.0" + win32_registry: + dependency: transitive + description: + name: win32_registry + sha256: "41fd8a189940d8696b1b810efb9abcf60827b6cbfab90b0c43e8439e3a39d85a" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: faea9dee56b520b55a566385b84f2e8de55e7496104adada9962e0bd11bcff1d + url: "https://pub.dev" + source: hosted + version: "1.0.4" +sdks: + dart: ">=3.2.3 <4.0.0" + flutter: ">=3.16.0" diff --git a/pdv/pubspec.yaml b/pdv/pubspec.yaml new file mode 100644 index 0000000..758e120 --- /dev/null +++ b/pdv/pubspec.yaml @@ -0,0 +1,96 @@ +name: pdv +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: '>=3.2.3 <4.0.0' + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + device_info_plus: ^9.1.0 + flutter: + sdk: flutter + flutter_barcode_scanner: ^2.0.0 + flutter_secure_storage: ^9.0.0 + http: ^1.2.0 + package_info_plus: ^4.2.0 + shared_preferences: ^2.2.2 + + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^2.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages diff --git a/pdv/test/cart_repository_test.dart b/pdv/test/cart_repository_test.dart new file mode 100644 index 0000000..cc4905e --- /dev/null +++ b/pdv/test/cart_repository_test.dart @@ -0,0 +1,55 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pdv/domain/entities/product.dart'; +import 'package:pdv/domain/repositories/cart_repository.dart'; + +void main() { + const product = Product( + id: 10, + code: 'P10', + grade: 'UN', + name: 'Caneca', + departmentCode: 1, + writeDate: '2026-11-12 12:00:00', + priceMinorUnits: 1234, + ); + + test('adiciona, altera quantidade e calcula total em centavos', () { + final cart = InMemoryCartRepository(); + cart.addProduct(product); + cart.increaseQuantity(product); + + expect(cart.items.single.quantity, 2); + expect(cart.itemCount, 2); + expect(cart.totalMinorUnits, 2468); + + cart.decreaseQuantity(product); + expect(cart.items.single.quantity, 1); + expect(cart.totalMinorUnits, 1234); + }); + + test('não reduz a quantidade abaixo de um; remover é explícito', () { + final cart = InMemoryCartRepository()..addProduct(product); + + cart.decreaseQuantity(product); + expect(cart.items.single.quantity, 1); + + cart.removeProduct(product); + expect(cart.items, isEmpty); + expect(cart.totalMinorUnits, 0); + }); + + test('não calcula total se algum item não tem preço', () { + final cart = InMemoryCartRepository() + ..addProduct(product) + ..addProduct(const Product( + id: 11, + code: 'P11', + grade: 'UN', + name: 'Item sem preço', + departmentCode: 1, + writeDate: '', + )); + + expect(cart.totalMinorUnits, isNull); + }); +} diff --git a/pdv/test/currency_formatter_test.dart b/pdv/test/currency_formatter_test.dart new file mode 100644 index 0000000..5ac9b58 --- /dev/null +++ b/pdv/test/currency_formatter_test.dart @@ -0,0 +1,14 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pdv/core/utils/currency_formatter.dart'; + +void main() { + test('formata BRL com símbolo e vírgula decimal', () { + expect(CurrencyFormatter.formatBrl(123456), r'R$ 1.234,56'); + expect(CurrencyFormatter.formatBrl(100), r'R$ 1,00'); + expect(CurrencyFormatter.formatBrl(0), r'R$ 0,00'); + }); + + test('não assume preço zero quando o valor está indisponível', () { + expect(CurrencyFormatter.formatBrl(null), 'Preço indisponível'); + }); +} diff --git a/pdv/test/odoo_auth_repository_test.dart b/pdv/test/odoo_auth_repository_test.dart new file mode 100644 index 0000000..7df3b1c --- /dev/null +++ b/pdv/test/odoo_auth_repository_test.dart @@ -0,0 +1,191 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:pdv/data/repositories/odoo_auth_repository.dart'; +import 'package:pdv/domain/entities/app_settings.dart'; +import 'package:pdv/domain/entities/pos_device.dart'; +import 'package:pdv/domain/repositories/auth_repository.dart'; +import 'package:pdv/core/storage/secure_session_storage.dart'; + +void main() { + const settings = AppSettings( + serverUrl: 'https://erp.example.com/odoo/', + companyIdentifier: 'EMPRESA01', + ); + const device = PosDevice( + platform: 'android', + serial: 'device-id', + model: 'POS model', + brand: 'POS brand', + ); + + test('login envia dados do operador/dispositivo e guarda cookie seguro', + () async { + final storage = MemorySessionStorage(); + final client = MockClient((request) async { + expect(request.method, 'POST'); + expect(request.url.path, '/odoo/pdv_pos/logar'); + expect(request.followRedirects, isFalse); + final body = Uri.splitQueryString(request.body); + expect(body['username'], 'operador'); + expect(body['password'], 'senha-do-odoo'); + expect(body['cnpj'], 'EMPRESA01'); + expect(body['serial'], 'device-id'); + expect(body['platform'], 'android'); + return http.Response( + jsonEncode({ + 'status': 'ok', + 'session_id': 'session-123', + 'user': {'id': 5, 'name': 'Operador'}, + 'company_id': 1, + }), + 200, + headers: {'set-cookie': 'sid=server-session; Path=/; HttpOnly; Secure'}, + ); + }); + final repository = OdooAuthRepository( + sessionStorage: storage, + client: client, + ); + + await repository.authenticate( + username: 'operador', + password: 'senha-do-odoo', + settings: settings, + device: device, + appVersion: '1.0.0', + ); + + expect(repository.isAuthenticated, isTrue); + expect(repository.currentSession?.userId, 5); + expect(repository.currentSession?.companyId, 1); + expect(storage.cookie, 'sid=server-session'); + expect(storage.serverUrl, settings.serverUrl); + expect(storage.sessionId, 'session-123'); + client.close(); + }); + + test('logout envia cookie e limpa armazenamento seguro', () async { + final storage = MemorySessionStorage() + ..cookie = 'sid=server-session' + ..serverUrl = settings.serverUrl + ..sessionId = 'session-123'; + final client = MockClient((request) async { + expect(request.url.path, '/odoo/pdv_pos/logout'); + expect(Uri.splitQueryString(request.body)['session_id'], 'session-123'); + expect(request.headers['cookie'], 'sid=server-session'); + return http.Response(jsonEncode({'status': 'ok'}), 200); + }); + final repository = OdooAuthRepository( + sessionStorage: storage, + client: client, + ); + // Simulates a fresh app process restoring the server URL for logout. + await repository.logout(); + + expect(storage.cookie, isNull); + expect(storage.serverUrl, isNull); + expect(storage.sessionId, isNull); + expect(repository.isAuthenticated, isFalse); + client.close(); + }); + + test('não declara login válido sem cookie de sessão do Odoo', () async { + final storage = MemorySessionStorage(); + final client = MockClient((_) async => http.Response( + jsonEncode({ + 'status': 'ok', + 'session_id': 'session-123', + 'user': {'id': 5} + }), + 200, + )); + final repository = OdooAuthRepository( + sessionStorage: storage, + client: client, + ); + + await expectLater( + repository.authenticate( + username: 'operador', + password: 'senha-do-odoo', + settings: settings, + device: device, + appVersion: '1.0.0', + ), + throwsA(isA()), + ); + expect(repository.isAuthenticated, isFalse); + client.close(); + }); + + test('Linux envia plataforma sem dados de dispositivo para pular licença', + () async { + final storage = MemorySessionStorage(); + final client = MockClient((request) async { + final body = Uri.splitQueryString(request.body); + expect(body['platform'], 'linux'); + expect(body.containsKey('serial'), isFalse); + expect(body.containsKey('model'), isFalse); + expect(body.containsKey('brand'), isFalse); + return http.Response( + jsonEncode({ + 'status': 'ok', + 'session_id': 'session-123', + 'user': {'id': 5} + }), + 200, + headers: {'set-cookie': 'sid=linux-session; Path=/; HttpOnly; Secure'}, + ); + }); + final repository = OdooAuthRepository( + sessionStorage: storage, + client: client, + ); + + await repository.authenticate( + username: 'operador', + password: 'senha-do-odoo', + settings: settings, + device: const PosDevice(platform: 'linux'), + appVersion: '1.0.0', + ); + + expect(repository.isAuthenticated, isTrue); + client.close(); + }); +} + +class MemorySessionStorage implements SecureSessionStorage { + String? cookie; + String? serverUrl; + String? sessionId; + + @override + Future clearCookie() async { + cookie = null; + serverUrl = null; + sessionId = null; + } + + @override + Future readCookie() async => cookie; + + @override + Future readServerUrl() async => serverUrl; + + @override + Future readSessionId() async => sessionId; + + @override + Future writeSession( + {required String cookie, + required String serverUrl, + required String sessionId}) async { + this.cookie = cookie; + this.serverUrl = serverUrl; + this.sessionId = sessionId; + } +} diff --git a/pdv/test/odoo_catalog_repository_test.dart b/pdv/test/odoo_catalog_repository_test.dart new file mode 100644 index 0000000..6850b61 --- /dev/null +++ b/pdv/test/odoo_catalog_repository_test.dart @@ -0,0 +1,183 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:pdv/data/repositories/odoo_catalog_repository.dart'; +import 'package:pdv/data/datasources/remote/odoo_session_api_client.dart'; +import 'package:pdv/domain/entities/app_settings.dart'; +import 'package:pdv/domain/entities/app_session.dart'; +import 'package:pdv/domain/entities/pos_device.dart'; +import 'package:pdv/domain/repositories/auth_repository.dart'; +import 'package:pdv/domain/repositories/catalog_repository.dart'; +import 'package:pdv/domain/repositories/settings_repository.dart'; +import 'package:pdv/core/storage/secure_session_storage.dart'; + +void main() { + const settings = AppSettings( + serverUrl: 'https://erp.example.com/odoo', + companyIdentifier: 'EMPRESA01', + ); + final auth = CatalogTestAuthRepository(); + const settingsRepository = CatalogTestSettingsRepository(settings); + final storage = CatalogTestSessionStorage() + ..cookie = 'sid=test-session' + ..sessionId = 'session-123'; + + OdooCatalogRepository repositoryWith(http.Client client) => + OdooCatalogRepository( + apiClient: OdooSessionApiClient( + authRepository: auth, + settingsRepository: settingsRepository, + sessionStorage: storage, + client: client, + ), + ); + + setUp(() { + auth.authenticated = true; + auth.session = + const AppSession(userId: 5, userName: 'Operador', companyId: 1); + }); + + test('carrega departamentos usando a sessão Odoo e somente id/nome', + () async { + final client = MockClient((request) async { + expect(request.method, 'GET'); + expect(request.url.path, '/odoo/pdv_pos/departamentos'); + expect(request.url.queryParameters['session_id'], 'session-123'); + expect(request.headers['cookie'], 'sid=test-session'); + return http.Response( + jsonEncode({ + 'status': 'ok', + 'departments': [ + {'id': 3, 'name': 'Acessórios'}, + ], + }), + 200, + ); + }); + final repository = repositoryWith(client); + + final departments = await repository.fetchDepartments(); + + expect(departments.single.id, 3); + expect(departments.single.name, 'Acessórios'); + client.close(); + }); + + test('carrega produtos do departamento solicitado', () async { + final client = MockClient((request) async { + expect(request.url.path, '/odoo/pdv_pos/produtos_por_departamento'); + expect(request.url.queryParameters['department_id'], '3'); + expect(request.url.queryParameters['session_id'], 'session-123'); + expect(request.headers['cookie'], 'sid=test-session'); + return http.Response( + jsonEncode({ + 'status': 'ok', + 'products': [ + { + 'id': 10, + 'codigo': 'P10', + 'grade': 'UN', + 'descricao': 'Produto teste', + 'departamento_id': 3, + 'preco': 12.34, + 'qtdEmEstoque': 4, + 'write_date': '2026-11-12 12:00:00', + }, + ], + }), + 200, + ); + }); + final repository = repositoryWith(client); + + final products = await repository.fetchProductsByDepartment(3); + + expect(products.single.id, 10); + expect(products.single.name, 'Produto teste'); + expect(products.single.priceMinorUnits, 1234); + client.close(); + }); + + test('recusa catálogo quando não há sessão autenticada', () async { + auth.authenticated = false; + final client = MockClient((_) async => http.Response('', 500)); + final repository = repositoryWith(client); + + await expectLater( + repository.fetchDepartments(), + throwsA(isA()), + ); + client.close(); + }); +} + +class CatalogTestAuthRepository implements AuthRepository { + bool authenticated = false; + AppSession? session; + + @override + bool get isAuthenticated => authenticated; + + @override + AppSession? get currentSession => session; + + @override + Future authenticate({ + required String username, + required String password, + required AppSettings settings, + required PosDevice device, + required String appVersion, + }) async => + throw UnimplementedError(); + + @override + Future logout() async { + authenticated = false; + session = null; + } +} + +class CatalogTestSettingsRepository implements SettingsRepository { + const CatalogTestSettingsRepository(this.settings); + + final AppSettings settings; + + @override + Future load() async => settings; + + @override + Future save(AppSettings settings) async {} +} + +class CatalogTestSessionStorage implements SecureSessionStorage { + String? cookie; + String? sessionId; + + @override + Future clearCookie() async { + cookie = null; + sessionId = null; + } + + @override + Future readCookie() async => cookie; + + @override + Future readServerUrl() async => null; + + @override + Future readSessionId() async => sessionId; + + @override + Future writeSession( + {required String cookie, + required String serverUrl, + required String sessionId}) async { + this.cookie = cookie; + this.sessionId = sessionId; + } +} diff --git a/pdv/test/odoo_checkout_repositories_test.dart b/pdv/test/odoo_checkout_repositories_test.dart new file mode 100644 index 0000000..2d26a93 --- /dev/null +++ b/pdv/test/odoo_checkout_repositories_test.dart @@ -0,0 +1,127 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:pdv/data/datasources/remote/odoo_session_api_client.dart'; +import 'package:pdv/data/repositories/odoo_customer_repository.dart'; +import 'package:pdv/data/repositories/odoo_payment_methods_repository.dart'; +import 'package:pdv/domain/entities/app_settings.dart'; +import 'package:pdv/domain/entities/app_session.dart'; +import 'package:pdv/core/storage/secure_session_storage.dart'; + +import 'support/test_app_services.dart'; + +void main() { + const settings = AppSettings( + serverUrl: 'https://erp.example.com/odoo', + companyIdentifier: 'EMPRESA01', + ); + + test('pesquisa cliente por POST e recebe apenas documento mascarado', + () async { + final testServices = _authenticatedServices(settings); + final client = MockClient((request) async { + expect(request.method, 'POST'); + expect(request.url.path, '/odoo/pdv_pos/clientes'); + expect(request.url.queryParameters, isEmpty); + final body = Uri.splitQueryString(request.body); + expect(body['session_id'], 'session-123'); + expect(body['query'], 'Maria'); + return http.Response( + jsonEncode({ + 'status': 'ok', + 'customers': [ + { + 'id': 12, + 'name': 'Maria da Silva', + 'document_masked': '123.***.**9-01', + }, + ], + }), + 200, + ); + }); + final repository = OdooCustomerRepository( + apiClient: _apiClient(testServices, client), + ); + + final customers = await repository.search('Maria'); + + expect(customers.single.name, 'Maria da Silva'); + expect(customers.single.documentMasked, '123.***.**9-01'); + client.close(); + }); + + test('carrega formas de pagamento dinâmicas', () async { + final testServices = _authenticatedServices(settings); + final client = MockClient((request) async { + expect(request.method, 'GET'); + expect(request.url.path, '/odoo/pdv_pos/formas_pagamento'); + expect(request.url.queryParameters['session_id'], 'session-123'); + return http.Response( + jsonEncode({ + 'status': 'ok', + 'payment_methods': [ + { + 'id': 4, + 'name': 'Dinheiro - À vista', + 'payment_type': '01', + 'condition_id': 2, + 'condition_type': 'V', + 'installments': 1, + }, + ], + }), + 200, + ); + }); + final repository = OdooPaymentMethodsRepository( + apiClient: _apiClient(testServices, client), + ); + + final methods = await repository.loadAvailable(); + + expect(methods.single.name, 'Dinheiro - À vista'); + expect(methods.single.paymentType, '01'); + expect(methods.single.installments, 1); + client.close(); + }); +} + +TestAppServices _authenticatedServices(AppSettings settings) { + final services = TestAppServices(initialSettings: settings); + services.authRepository + ..authenticated = true + ..session = const AppSession(userId: 5, userName: 'Operador', companyId: 1); + return services; +} + +OdooSessionApiClient _apiClient(TestAppServices services, http.Client client) => + OdooSessionApiClient( + authRepository: services.authRepository, + settingsRepository: services.settingsRepository, + sessionStorage: CheckoutSessionStorage(), + client: client, + ); + +class CheckoutSessionStorage implements SecureSessionStorage { + @override + Future clearCookie() async {} + + @override + Future readCookie() async => 'sid=test-session'; + + @override + Future readServerUrl() async => null; + + @override + Future readSessionId() async => 'session-123'; + + @override + Future writeSession({ + required String cookie, + required String serverUrl, + required String sessionId, + }) async {} +} diff --git a/pdv/test/odoo_connection_tester_test.dart b/pdv/test/odoo_connection_tester_test.dart new file mode 100644 index 0000000..7381e1a --- /dev/null +++ b/pdv/test/odoo_connection_tester_test.dart @@ -0,0 +1,69 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:pdv/data/datasources/remote/odoo_connection_tester.dart'; + +void main() { + test('consulta health check e aceita apenas contrato esperado', () async { + late Uri requestedUri; + final client = MockClient((request) async { + requestedUri = request.url; + return http.Response( + jsonEncode({'status': 'ok', 'api_version': 1}), + 200, + headers: {'content-type': 'application/json'}, + ); + }); + final tester = OdooConnectionTester(client: client); + + final result = + await tester.test(Uri.parse('https://erp.example.com/odoo/')); + + expect( + requestedUri, Uri.parse('https://erp.example.com/odoo/pdv_pos/health')); + expect(result.isAvailable, isTrue); + client.close(); + }); + + test('não considera saudável resposta de outro contrato', () async { + final client = MockClient((_) async => http.Response( + jsonEncode({'status': 'ok', 'api_version': 2}), + 200, + )); + final tester = OdooConnectionTester(client: client); + + final result = await tester.test(Uri.parse('https://erp.example.com')); + + expect(result.isAvailable, isFalse); + expect(result.message, contains('não confirmou')); + client.close(); + }); + + test('trata erro HTTP como falha de conexão', () async { + final client = MockClient((_) async => http.Response('', 404)); + final tester = OdooConnectionTester(client: client); + + final result = await tester.test(Uri.parse('https://erp.example.com')); + + expect(result.isAvailable, isFalse); + expect(result.message, contains('404')); + client.close(); + }); + + test('não segue redirecionamento do endpoint', () async { + var followedRedirects = true; + final client = MockClient((request) async { + followedRedirects = request.followRedirects; + return http.Response('', 302); + }); + final tester = OdooConnectionTester(client: client); + + final result = await tester.test(Uri.parse('https://erp.example.com')); + + expect(followedRedirects, isFalse); + expect(result.isAvailable, isFalse); + client.close(); + }); +} diff --git a/pdv/test/sale_view_preference_repository_test.dart b/pdv/test/sale_view_preference_repository_test.dart new file mode 100644 index 0000000..baf26ba --- /dev/null +++ b/pdv/test/sale_view_preference_repository_test.dart @@ -0,0 +1,19 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pdv/data/repositories/shared_preferences_sale_view_preference_repository.dart'; +import 'package:pdv/domain/entities/sale_view_mode.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('salva a preferência por usuário sem afetar outro usuário', () async { + SharedPreferences.setMockInitialValues({}); + const repository = SharedPreferencesSaleViewPreferenceRepository(); + + await repository.saveForUser(7, SaleViewMode.list); + await repository.saveForUser(8, SaleViewMode.kanban); + + expect(await repository.loadForUser(7), SaleViewMode.list); + expect(await repository.loadForUser(8), SaleViewMode.kanban); + }); +} diff --git a/pdv/test/server_url_validator_test.dart b/pdv/test/server_url_validator_test.dart new file mode 100644 index 0000000..d2ac8ab --- /dev/null +++ b/pdv/test/server_url_validator_test.dart @@ -0,0 +1,38 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pdv/core/config/server_url_validator.dart'; + +void main() { + group('ServerUrlValidator', () { + test('aceita URL HTTPS com host', () { + expect(ServerUrlValidator.validate('https://odoo.example.com'), isNull); + }); + + test('rejeita URL HTTP sem criptografia', () { + expect( + ServerUrlValidator.validate( + 'http://odoo.example.com', + requireHttps: true, + ), + contains('HTTPS'), + ); + }); + + test('aceita HTTP por padrão nas configurações', () { + expect(ServerUrlValidator.validate('http://odoo.local'), isNull); + }); + + test('permite HTTP quando HTTPS não é obrigatório', () { + expect( + ServerUrlValidator.validate( + 'http://odoo.local', + requireHttps: false, + ), + isNull, + ); + }); + + test('rejeita URL sem host', () { + expect(ServerUrlValidator.validate('https://'), isNotNull); + }); + }); +} diff --git a/pdv/test/shared_preferences_settings_repository_test.dart b/pdv/test/shared_preferences_settings_repository_test.dart new file mode 100644 index 0000000..311d2bd --- /dev/null +++ b/pdv/test/shared_preferences_settings_repository_test.dart @@ -0,0 +1,21 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pdv/data/repositories/shared_preferences_settings_repository.dart'; +import 'package:pdv/domain/entities/app_settings.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('persiste URL e identificador sem dados sensíveis', () async { + SharedPreferences.setMockInitialValues({}); + const repository = SharedPreferencesSettingsRepository(); + const settings = AppSettings( + serverUrl: 'https://odoo.example.com', + companyIdentifier: 'EMPRESA123', + ); + + await repository.save(settings); + + expect(await repository.load(), settings); + }); +} diff --git a/pdv/test/support/test_app_services.dart b/pdv/test/support/test_app_services.dart new file mode 100644 index 0000000..3ba9b7f --- /dev/null +++ b/pdv/test/support/test_app_services.dart @@ -0,0 +1,261 @@ +import 'package:pdv/app/app_services.dart'; +import 'package:pdv/domain/entities/app_settings.dart'; +import 'package:pdv/domain/entities/app_session.dart'; +import 'package:pdv/domain/entities/cart_item.dart'; +import 'package:pdv/domain/entities/customer.dart'; +import 'package:pdv/domain/entities/department.dart'; +import 'package:pdv/domain/entities/payment_method.dart'; +import 'package:pdv/domain/entities/sale_completion.dart'; +import 'package:pdv/domain/entities/historical_sale.dart'; +import 'package:pdv/domain/entities/sale_payment.dart'; +import 'package:pdv/domain/entities/product.dart'; +import 'package:pdv/domain/entities/sale_view_mode.dart'; +import 'package:pdv/domain/entities/pos_device.dart'; +import 'package:pdv/domain/repositories/auth_repository.dart'; +import 'package:pdv/domain/repositories/cart_repository.dart'; +import 'package:pdv/domain/repositories/catalog_repository.dart'; +import 'package:pdv/domain/repositories/customer_repository.dart'; +import 'package:pdv/domain/repositories/connection_tester.dart'; +import 'package:pdv/domain/repositories/payment_methods_repository.dart'; +import 'package:pdv/domain/repositories/sale_checkout_repository.dart'; +import 'package:pdv/domain/repositories/sales_history_repository.dart'; +import 'package:pdv/domain/repositories/settings_repository.dart'; +import 'package:pdv/domain/repositories/sale_view_preference_repository.dart'; +import 'package:pdv/core/config/app_version_provider.dart'; +import 'package:pdv/core/config/pos_device_provider.dart'; + +class TestAppServices { + TestAppServices({AppSettings? initialSettings}) + : settingsRepository = MemorySettingsRepository(initialSettings), + authRepository = TestAuthRepository(), + connectionTester = TestConnectionTester(), + appVersionProvider = TestAppVersionProvider(), + posDeviceProvider = TestPosDeviceProvider(), + catalogRepository = TestCatalogRepository(), + cartRepository = InMemoryCartRepository(), + saleViewPreferenceRepository = TestSaleViewPreferenceRepository(), + customerRepository = TestCustomerRepository(), + paymentMethodsRepository = TestPaymentMethodsRepository(), + saleCheckoutRepository = TestSaleCheckoutRepository(), + salesHistoryRepository = TestSalesHistoryRepository(); + + final MemorySettingsRepository settingsRepository; + final TestAuthRepository authRepository; + final TestConnectionTester connectionTester; + final TestAppVersionProvider appVersionProvider; + final TestPosDeviceProvider posDeviceProvider; + final TestCatalogRepository catalogRepository; + final InMemoryCartRepository cartRepository; + final TestSaleViewPreferenceRepository saleViewPreferenceRepository; + final TestCustomerRepository customerRepository; + final TestPaymentMethodsRepository paymentMethodsRepository; + final TestSaleCheckoutRepository saleCheckoutRepository; + final TestSalesHistoryRepository salesHistoryRepository; + + AppServices get services => AppServices( + settingsRepository: settingsRepository, + connectionTester: connectionTester, + authRepository: authRepository, + appVersionProvider: appVersionProvider, + posDeviceProvider: posDeviceProvider, + catalogRepository: catalogRepository, + cartRepository: cartRepository, + saleViewPreferenceRepository: saleViewPreferenceRepository, + customerRepository: customerRepository, + paymentMethodsRepository: paymentMethodsRepository, + saleCheckoutRepository: saleCheckoutRepository, + salesHistoryRepository: salesHistoryRepository, + ); +} + +class MemorySettingsRepository implements SettingsRepository { + MemorySettingsRepository(this.settings); + + AppSettings? settings; + + @override + Future load() async => settings; + + @override + Future save(AppSettings value) async { + settings = value; + } +} + +class TestAuthRepository implements AuthRepository { + bool authenticated = false; + bool shouldAuthenticate = false; + int logoutCount = 0; + int userId = 7; + AppSession? session; + String? lastUsername; + AppSettings? lastSettings; + PosDevice? lastDevice; + String? lastAppVersion; + + @override + bool get isAuthenticated => authenticated; + + @override + AppSession? get currentSession => session; + + @override + Future authenticate({ + required String username, + required String password, + required AppSettings settings, + required PosDevice device, + required String appVersion, + }) async { + lastUsername = username; + lastSettings = settings; + lastDevice = device; + lastAppVersion = appVersion; + if (!shouldAuthenticate) { + throw const AuthUnavailableException( + 'Contrato de teste não configurado.'); + } + authenticated = true; + session = AppSession(userId: userId, userName: 'Operador', companyId: 1); + return session!; + } + + @override + Future logout() async { + logoutCount++; + authenticated = false; + session = null; + } +} + +class TestConnectionTester implements ConnectionTester { + int callCount = 0; + + @override + Future test(Uri serverUri) async { + callCount++; + return const ConnectionTestResult( + isAvailable: false, + message: 'Endpoint de teste não configurado.', + ); + } +} + +class TestAppVersionProvider implements AppVersionProvider { + @override + Future getVersion() async => '9.8.7'; +} + +class TestPosDeviceProvider implements PosDeviceProvider { + String platform = 'android'; + + @override + Future getDevice() async { + if (platform != 'android') return PosDevice(platform: platform); + return const PosDevice( + platform: 'android', + serial: 'test-device', + model: 'test-model', + brand: 'test-brand', + ); + } +} + +class TestCatalogRepository implements CatalogRepository { + List departments = []; + final Map> productsByDepartment = {}; + final Map productFetchCountByDepartment = {}; + Object? error; + final Map productsByBarcode = {}; + + @override + Future> fetchDepartments() async { + if (error != null) throw error!; + return departments; + } + + @override + Future> fetchProductsByDepartment(int departmentId) async { + if (error != null) throw error!; + productFetchCountByDepartment[departmentId] = + (productFetchCountByDepartment[departmentId] ?? 0) + 1; + return productsByDepartment[departmentId] ?? []; + } + + @override + Future fetchProductByBarcode(String barcode) async { + if (error != null) throw error!; + return productsByBarcode[barcode]; + } +} + +class TestSaleViewPreferenceRepository implements SaleViewPreferenceRepository { + final Map preferencesByUser = {}; + + @override + Future loadForUser(int userId) async => + preferencesByUser[userId] ?? SaleViewMode.kanban; + + @override + Future saveForUser(int userId, SaleViewMode mode) async { + preferencesByUser[userId] = mode; + } +} + +class TestCustomerRepository implements CustomerRepository { + List results = []; + String? lastQuery; + Object? error; + + @override + Future> search(String query) async { + lastQuery = query; + if (error != null) throw error!; + return results; + } +} + +class TestPaymentMethodsRepository implements PaymentMethodsRepository { + List methods = []; + Object? error; + + @override + Future> loadAvailable() async { + if (error != null) throw error!; + return methods; + } +} + +class TestSaleCheckoutRepository implements SaleCheckoutRepository { + SaleCompletion? completion; + SaleCheckoutException? error; + + @override + Future finalizeCashSale({ + required List items, + required List payments, + Customer? customer, + String? customerCpf, + required String checkoutKey, + }) async { + if (error != null) throw error!; + return completion ?? + const SaleCompletion( + orderNumber: 'PVE-TEST', + invoiceId: 1, + invoiceNumber: '1', + invoiceSeries: '1', + ); + } +} + +class TestSalesHistoryRepository implements SalesHistoryRepository { + List sales = []; + Object? error; + + @override + Future> fetchSales() async { + if (error != null) throw error!; + return sales; + } +} diff --git a/pdv/test/widget_test.dart b/pdv/test/widget_test.dart new file mode 100644 index 0000000..70d6cd6 --- /dev/null +++ b/pdv/test/widget_test.dart @@ -0,0 +1,411 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pdv/app/app.dart'; +import 'package:pdv/app/router/app_router.dart'; +import 'package:pdv/domain/entities/app_settings.dart'; +import 'package:pdv/domain/entities/app_session.dart'; +import 'package:pdv/domain/entities/department.dart'; +import 'package:pdv/domain/entities/customer.dart'; +import 'package:pdv/domain/entities/payment_method.dart'; +import 'package:pdv/domain/entities/product.dart'; +import 'package:pdv/domain/entities/sale_view_mode.dart'; + +import 'support/test_app_services.dart'; + +void main() { + testWidgets('abre no login e acessa configuração pela engrenagem', + (WidgetTester tester) async { + final testServices = TestAppServices(); + await tester.pumpWidget(PdvApp(services: testServices.services)); + + await tester.pumpAndSettle(); + expect(find.text('Acesso ao PDV'), findsOneWidget); + expect(find.text('Versão: 9.8.7'), findsOneWidget); + expect(find.byType(BackButton), findsNothing); + expect(find.byTooltip('Configuração'), findsOneWidget); + expect(find.text('Configurar servidor'), findsNothing); + await tester.tap(find.byTooltip('Configuração')); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('settings-server-url')), findsOneWidget); + expect(find.byType(BackButton), findsNothing); + }); + + testWidgets('redireciona rota protegida para login sem sessão', + (WidgetTester tester) async { + final testServices = TestAppServices(); + await tester.pumpWidget(PdvApp(services: testServices.services)); + PdvApp.navigatorKey.currentState!.pushNamed(AppRoutes.salesHistory); + await tester.pumpAndSettle(); + + expect(find.text('Acesso ao PDV'), findsOneWidget); + expect(find.text('Histórico de vendas'), findsNothing); + }); + + testWidgets('valida campos obrigatórios do login', + (WidgetTester tester) async { + final testServices = TestAppServices(); + await tester.pumpWidget(PdvApp(services: testServices.services)); + await tester.ensureVisible(find.text('Entrar')); + await tester.tap(find.text('Entrar')); + await tester.pumpAndSettle(); + + expect(find.text('Informe o usuário.'), findsOneWidget); + expect(find.text('Informe a senha.'), findsOneWidget); + }); + + testWidgets( + 'envia usuário, configuração e dispositivo ao repositório de login', + (WidgetTester tester) async { + const settings = AppSettings( + serverUrl: 'https://odoo.example.com', + companyIdentifier: 'EMPRESA123', + ); + final testServices = TestAppServices(initialSettings: settings); + testServices.authRepository.shouldAuthenticate = true; + await tester.pumpWidget(PdvApp(services: testServices.services)); + + await tester.enterText(find.byKey(const Key('login-username')), 'operador'); + await tester.enterText(find.byKey(const Key('login-password')), 'senha'); + await tester.ensureVisible(find.text('Entrar')); + await tester.tap(find.text('Entrar')); + await tester.pumpAndSettle(); + + expect(find.text('Venda'), findsWidgets); + expect(testServices.authRepository.lastUsername, 'operador'); + expect(testServices.authRepository.lastSettings, settings); + expect(testServices.authRepository.lastDevice?.serial, 'test-device'); + expect(testServices.authRepository.lastAppVersion, '9.8.7'); + }); + + testWidgets('mostra catálogo por departamento e adiciona produto ao carrinho', + (WidgetTester tester) async { + const settings = AppSettings( + serverUrl: 'https://odoo.example.com', + companyIdentifier: 'EMPRESA123', + ); + final testServices = TestAppServices(initialSettings: settings); + testServices.authRepository.shouldAuthenticate = true; + testServices.catalogRepository.departments = const [ + Department(id: 1, name: 'Acessórios'), + Department(id: 2, name: 'Bebidas'), + ]; + testServices.catalogRepository.productsByDepartment[1] = const [ + Product( + id: 10, + code: 'P10', + grade: 'UN', + name: 'Caneca', + departmentCode: 1, + writeDate: '2026-11-12 12:00:00', + priceMinorUnits: 1234, + stock: 4, + ), + ]; + await tester.pumpWidget(PdvApp(services: testServices.services)); + await tester.enterText(find.byKey(const Key('login-username')), 'operador'); + await tester.enterText(find.byKey(const Key('login-password')), 'senha'); + await tester.ensureVisible(find.text('Entrar')); + await tester.tap(find.text('Entrar')); + await tester.pumpAndSettle(); + + expect(find.text('Acessórios'), findsNWidgets(2)); + expect(find.text('Caneca'), findsOneWidget); + expect(testServices.catalogRepository.productFetchCountByDepartment[1], 1); + await tester.tap(find.byKey(const Key('refresh-products-button'))); + await tester.pumpAndSettle(); + expect(testServices.catalogRepository.productFetchCountByDepartment[1], 2); + + await tester.tap(find.byTooltip('Adicionar Caneca')); + await tester.pumpAndSettle(); + + expect(find.text('Total do carrinho'), findsOneWidget); + expect(find.text('R\$ 12,34'), findsNWidgets(2)); + expect(find.text('1'), findsOneWidget); + await tester.tap(find.byTooltip('Visualizar em lista')); + await tester.pumpAndSettle(); + expect(find.byTooltip('Visualizar em Kanban'), findsOneWidget); + }); + + testWidgets('restaura e salva visualização por usuário', + (WidgetTester tester) async { + const settings = AppSettings( + serverUrl: 'https://odoo.example.com', + companyIdentifier: 'EMPRESA123', + ); + final testServices = TestAppServices(initialSettings: settings); + testServices.authRepository.shouldAuthenticate = true; + testServices.saleViewPreferenceRepository.preferencesByUser[7] = + SaleViewMode.list; + testServices.catalogRepository.departments = const [ + Department(id: 1, name: 'Acessórios'), + ]; + testServices.catalogRepository.productsByDepartment[1] = const [ + Product( + id: 10, + code: 'P10', + grade: 'UN', + name: 'Caneca', + departmentCode: 1, + writeDate: '2026-11-12 12:00:00', + priceMinorUnits: 1234, + ), + ]; + await tester.pumpWidget(PdvApp(services: testServices.services)); + await tester.enterText(find.byKey(const Key('login-username')), 'operador'); + await tester.enterText(find.byKey(const Key('login-password')), 'senha'); + await tester.ensureVisible(find.text('Entrar')); + await tester.tap(find.text('Entrar')); + await tester.pumpAndSettle(); + + expect(find.byTooltip('Visualizar em Kanban'), findsOneWidget); + await tester.tap(find.byTooltip('Visualizar em Kanban')); + await tester.pumpAndSettle(); + expect( + testServices.saleViewPreferenceRepository.preferencesByUser[7], + SaleViewMode.kanban, + ); + expect(find.byTooltip('Visualizar em lista'), findsOneWidget); + }); + + testWidgets('permite ajustar, remover e limpar o carrinho com confirmação', + (WidgetTester tester) async { + final testServices = TestAppServices(); + testServices.authRepository + ..authenticated = true + ..session = + const AppSession(userId: 7, userName: 'Operador', companyId: 1); + const product = Product( + id: 10, + code: 'P10', + grade: 'UN', + name: 'Caneca', + departmentCode: 1, + writeDate: '2026-11-12 12:00:00', + priceMinorUnits: 1234, + ); + testServices.cartRepository.addProduct(product); + await tester.pumpWidget(PdvApp(services: testServices.services)); + PdvApp.navigatorKey.currentState!.pushNamed(AppRoutes.cart); + await tester.pumpAndSettle(); + + expect(find.text('Caneca'), findsOneWidget); + expect(find.text('Unitário: R\$ 12,34'), findsOneWidget); + expect(find.text('Subtotal: R\$ 12,34'), findsOneWidget); + expect(find.text(r'R$ 12,34'), findsOneWidget); + await tester.tap(find.byKey(const Key('increase-10:UN'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('quantity-10:UN')), findsOneWidget); + expect(find.text('Subtotal: R\$ 24,68'), findsOneWidget); + expect(find.text(r'R$ 24,68'), findsOneWidget); + + await tester.tap(find.byKey(const Key('decrease-10:UN'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('remove-10:UN'))); + await tester.pumpAndSettle(); + expect(find.text('Carrinho vazio'), findsOneWidget); + + testServices.cartRepository.addProduct(product); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('Limpar carrinho')); + await tester.pumpAndSettle(); + expect(find.text('Limpar carrinho?'), findsOneWidget); + await tester.tap(find.text('Cancelar')); + await tester.pumpAndSettle(); + expect(find.text('Caneca'), findsOneWidget); + + await tester.tap(find.byTooltip('Limpar carrinho')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Limpar').last); + await tester.pumpAndSettle(); + expect(find.text('Carrinho vazio'), findsOneWidget); + }); + + testWidgets('consulta cliente mascarado e exibe pagamento retornado do Odoo', + (WidgetTester tester) async { + final testServices = TestAppServices(); + testServices.authRepository + ..authenticated = true + ..session = + const AppSession(userId: 7, userName: 'Operador', companyId: 1); + testServices.cartRepository.addProduct(const Product( + id: 22, + code: 'P22', + grade: 'UN', + name: 'Item de venda', + departmentCode: 1, + writeDate: '2026-11-12 12:00:00', + priceMinorUnits: 550, + )); + testServices.customerRepository.results = const [ + Customer( + id: 5, + name: 'Maria da Silva', + documentMasked: '123.***.**9-01', + ), + ]; + testServices.paymentMethodsRepository.methods = const [ + PaymentMethod( + id: 4, + name: 'Dinheiro - À vista', + paymentType: '01', + conditionId: 2, + conditionType: 'V', + installments: 1, + ), + PaymentMethod( + id: 5, + name: 'PIX - À vista', + paymentType: '17', + conditionId: 2, + conditionType: 'V', + installments: 1, + ), + PaymentMethod( + id: 6, + name: 'Cartão de Crédito - À vista', + paymentType: '03', + conditionId: 2, + conditionType: 'V', + installments: 1, + ), + PaymentMethod( + id: 7, + name: 'Cartão de Débito - À vista', + paymentType: '04', + conditionId: 2, + conditionType: 'V', + installments: 1, + ), + ]; + await tester.pumpWidget(PdvApp(services: testServices.services)); + PdvApp.navigatorKey.currentState!.pushNamed(AppRoutes.payment); + await tester.pumpAndSettle(); + + expect(find.text('Dinheiro'), findsOneWidget); + expect(find.text('PIX'), findsOneWidget); + expect(find.text('Cartão de Crédito'), findsOneWidget); + expect(find.text('Cartão de Débito'), findsOneWidget); + await tester.tap(find.byKey(const Key('payment-category-cash'))); + await tester.pumpAndSettle(); + expect(find.text('Valor desta parcela'), findsOneWidget); + await tester.tap(find.text('Adicionar')); + await tester.pumpAndSettle(); + expect(find.text('Dinheiro recebido: R\$ 5,50'), findsOneWidget); + await tester.ensureVisible(find.text('Incluir cliente')); + await tester.tap(find.text('Incluir cliente')); + await tester.pumpAndSettle(); + + await tester.enterText( + find.byKey(const Key('customer-search-query')), + 'Maria', + ); + await tester.tap(find.byTooltip('Pesquisar cliente')); + await tester.pumpAndSettle(); + expect(find.text('123.***.**9-01'), findsOneWidget); + await tester.tap(find.byKey(const Key('customer-5'))); + await tester.pumpAndSettle(); + + expect(find.text('Maria da Silva'), findsOneWidget); + expect(find.text('123.***.**9-01'), findsOneWidget); + expect(find.text('Finalizar venda'), findsOneWidget); + }); + + testWidgets('permite login de desenvolvimento no Linux sem dados de licença', + (WidgetTester tester) async { + const settings = AppSettings( + serverUrl: 'https://odoo.example.com', + companyIdentifier: 'EMPRESA123', + ); + final testServices = TestAppServices(initialSettings: settings); + testServices.posDeviceProvider.platform = 'linux'; + testServices.authRepository.shouldAuthenticate = true; + await tester.pumpWidget(PdvApp(services: testServices.services)); + + await tester.enterText(find.byKey(const Key('login-username')), 'operador'); + await tester.enterText(find.byKey(const Key('login-password')), 'senha'); + await tester.ensureVisible(find.text('Entrar')); + await tester.tap(find.text('Entrar')); + await tester.pumpAndSettle(); + + expect(find.text('Venda'), findsWidgets); + expect(testServices.authRepository.lastUsername, 'operador'); + expect(testServices.authRepository.lastDevice?.platform, 'linux'); + expect(testServices.authRepository.lastDevice?.serial, isNull); + }); + + testWidgets('valida e salva configuração, invalidando a sessão anterior', + (WidgetTester tester) async { + final testServices = TestAppServices(); + await tester.pumpWidget(PdvApp(services: testServices.services)); + await tester.tap(find.byTooltip('Configuração')); + await tester.pumpAndSettle(); + + await tester.enterText( + find.byKey(const Key('settings-server-url')), + 'https://odoo.example.com', + ); + await tester.enterText( + find.byKey(const Key('settings-company-identifier')), + 'EMPRESA123', + ); + await tester.ensureVisible(find.text('Salvar')); + await tester.tap(find.text('Salvar')); + await tester.pumpAndSettle(); + + expect(testServices.settingsRepository.settings?.serverUrl, + 'https://odoo.example.com'); + expect(testServices.settingsRepository.settings?.companyIdentifier, + 'EMPRESA123'); + expect(testServices.authRepository.logoutCount, 1); + expect(find.text('Configuração salva.'), findsOneWidget); + await tester.pumpAndSettle(); + expect(find.text('Acesso ao PDV'), findsOneWidget); + }); + + testWidgets('remove caracteres não alfanuméricos do identificador', + (WidgetTester tester) async { + final testServices = TestAppServices(); + await tester.pumpWidget(PdvApp(services: testServices.services)); + await tester.tap(find.byTooltip('Configuração')); + await tester.pumpAndSettle(); + + await tester.enterText( + find.byKey(const Key('settings-server-url')), + 'https://odoo.example.com', + ); + await tester.enterText( + find.byKey(const Key('settings-company-identifier')), + 'EMPRESA-123', + ); + + final identifierField = tester.widget( + find.byKey(const Key('settings-company-identifier')), + ); + expect(identifierField.controller!.text, 'EMPRESA123'); + expect(testServices.settingsRepository.settings, isNull); + }); + + testWidgets('não declara sucesso no teste sem endpoint configurado', + (WidgetTester tester) async { + final testServices = TestAppServices(); + await tester.pumpWidget(PdvApp(services: testServices.services)); + await tester.tap(find.byTooltip('Configuração')); + await tester.pumpAndSettle(); + + await tester.enterText( + find.byKey(const Key('settings-server-url')), + 'https://odoo.example.com', + ); + await tester.enterText( + find.byKey(const Key('settings-company-identifier')), + 'EMPRESA123', + ); + await tester.ensureVisible(find.byKey(const Key('test-connection-button'))); + await tester.tap(find.byKey(const Key('test-connection-button'))); + await tester.pumpAndSettle(); + + expect(find.text('Endpoint de teste não configurado.'), findsOneWidget); + expect(testServices.connectionTester.callCount, 1); + }); +} diff --git a/pdv/web/favicon.png b/pdv/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/pdv/web/favicon.png differ diff --git a/pdv/web/icons/Icon-192.png b/pdv/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/pdv/web/icons/Icon-192.png differ diff --git a/pdv/web/icons/Icon-512.png b/pdv/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/pdv/web/icons/Icon-512.png differ diff --git a/pdv/web/icons/Icon-maskable-192.png b/pdv/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/pdv/web/icons/Icon-maskable-192.png differ diff --git a/pdv/web/icons/Icon-maskable-512.png b/pdv/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/pdv/web/icons/Icon-maskable-512.png differ diff --git a/pdv/web/index.html b/pdv/web/index.html new file mode 100644 index 0000000..3348ad6 --- /dev/null +++ b/pdv/web/index.html @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + pdv + + + + + + + + + + diff --git a/pdv/web/manifest.json b/pdv/web/manifest.json new file mode 100644 index 0000000..1c6ccba --- /dev/null +++ b/pdv/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "pdv", + "short_name": "pdv", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/pdv/windows/.gitignore b/pdv/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/pdv/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/pdv/windows/CMakeLists.txt b/pdv/windows/CMakeLists.txt new file mode 100644 index 0000000..758fe18 --- /dev/null +++ b/pdv/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(pdv LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "pdv") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/pdv/windows/flutter/CMakeLists.txt b/pdv/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/pdv/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/pdv/windows/flutter/generated_plugin_registrant.cc b/pdv/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..0c50753 --- /dev/null +++ b/pdv/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FlutterSecureStorageWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin")); +} diff --git a/pdv/windows/flutter/generated_plugin_registrant.h b/pdv/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/pdv/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/pdv/windows/flutter/generated_plugins.cmake b/pdv/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..4fc759c --- /dev/null +++ b/pdv/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_secure_storage_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/pdv/windows/runner/CMakeLists.txt b/pdv/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/pdv/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/pdv/windows/runner/Runner.rc b/pdv/windows/runner/Runner.rc new file mode 100644 index 0000000..59c55dc --- /dev/null +++ b/pdv/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "pdv" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "pdv" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "pdv.exe" "\0" + VALUE "ProductName", "pdv" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/pdv/windows/runner/flutter_window.cpp b/pdv/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/pdv/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/pdv/windows/runner/flutter_window.h b/pdv/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/pdv/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/pdv/windows/runner/main.cpp b/pdv/windows/runner/main.cpp new file mode 100644 index 0000000..d22aa08 --- /dev/null +++ b/pdv/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"pdv", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/pdv/windows/runner/resource.h b/pdv/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/pdv/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/pdv/windows/runner/resources/app_icon.ico b/pdv/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/pdv/windows/runner/resources/app_icon.ico differ diff --git a/pdv/windows/runner/runner.exe.manifest b/pdv/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..a42ea76 --- /dev/null +++ b/pdv/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/pdv/windows/runner/utils.cpp b/pdv/windows/runner/utils.cpp new file mode 100644 index 0000000..b2b0873 --- /dev/null +++ b/pdv/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length <= 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/pdv/windows/runner/utils.h b/pdv/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/pdv/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/pdv/windows/runner/win32_window.cpp b/pdv/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/pdv/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/pdv/windows/runner/win32_window.h b/pdv/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/pdv/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_