commit 4a4113ec594e1796f7d7a00407a47494a66f1c0b Author: Pablinux Date: Sun Jun 14 09:18:18 2026 -0500 feat: Agente Ventas SIGMAC — app de rutas y pedidos de campo App Flutter 2.11 para vendedores de ruta de Telcotronics. Incluye ruta del día con mapa custom, catálogo, pedidos CRUD, firma digital, scanner QR/barcode, selector de clientes escalable, notificaciones in-app y soporte multiplataforma (Android + Linux desktop). Co-Authored-By: Claude Sonnet 4.6 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2bd531d --- /dev/null +++ b/.gitignore @@ -0,0 +1,49 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ + +# 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 +.packages +.pub-cache/ +.pub/ +/build/ + +# Web related +lib/generated_plugin_registrant.dart + +# 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 + +# Documentación interna de agentes IA (contiene IPs y credenciales) +.agente/ diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..7d83d11 --- /dev/null +++ b/.metadata @@ -0,0 +1,10 @@ +# 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: b101bfe32f634566e7cb2791a9efe19cf8828b15 + channel: dev + +project_type: app diff --git a/README.md b/README.md new file mode 100644 index 0000000..ec59b25 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# pedidos_app + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook) + +For help getting started with Flutter, view our +[online documentation](https://flutter.dev/docs), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..61b6c4d --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,29 @@ +# 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-lang.github.io/linter/lints/index.html. + # + # 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/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..6f56801 --- /dev/null +++ b/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/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..a8b6e62 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,69 @@ +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterRoot = localProperties.getProperty('flutter.sdk') +if (flutterRoot == null) { + throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" + +android { + compileSdkVersion flutter.compileSdkVersion + 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.sigmac.agenteventas" + 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 { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..25f3976 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..2b11106 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/sigmac/agenteventas/MainActivity.kt b/android/app/src/main/kotlin/com/sigmac/agenteventas/MainActivity.kt new file mode 100644 index 0000000..8c25976 --- /dev/null +++ b/android/app/src/main/kotlin/com/sigmac/agenteventas/MainActivity.kt @@ -0,0 +1,6 @@ +package com.sigmac.agenteventas + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() { +} diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..3db14bb --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..d460d1e --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..25f3976 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 0000000..4256f91 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,31 @@ +buildscript { + ext.kotlin_version = '1.6.10' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:4.1.0' + 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') +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..94adc3a --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx1536M +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..bc6a58a --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Jun 23 08:50:38 CEST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..44e62bc --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,11 @@ +include ':app' + +def localPropertiesFile = new File(rootProject.projectDir, "local.properties") +def properties = new Properties() + +assert localPropertiesFile.exists() +localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } + +def flutterSdkPath = properties.getProperty("flutter.sdk") +assert flutterSdkPath != null, "flutter.sdk not set in local.properties" +apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" diff --git a/assets/icon/icon.png b/assets/icon/icon.png new file mode 100644 index 0000000..2305b4a Binary files /dev/null and b/assets/icon/icon.png differ diff --git a/assets/icon/icon.svg b/assets/icon/icon.svg new file mode 100644 index 0000000..d673c16 --- /dev/null +++ b/assets/icon/icon.svg @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/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/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..8d4492f --- /dev/null +++ b/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 + 9.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..060169d --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,481 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + 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 */; }; +/* End PBXBuildFile 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 = ""; }; +/* 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 = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + ); + 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 */ + 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 = { + LastUpgradeCheck = 1300; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 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 */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 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; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + 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; + 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 */ + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase 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 = 9.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.pedidosapp.pedidosApp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + 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 = 9.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 = 9.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.pedidosapp.pedidosApp; + 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.pedidosapp.pedidosApp; + 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 */ + 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/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..c87d15a --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..70693e4 --- /dev/null +++ b/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/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/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/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..28c6bf0 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..2ccbfd9 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..f091b6b Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cde121 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..d0ef06e Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..dcdc230 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..2ccbfd9 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..c8f9ed8 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..a6d6b86 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..a6d6b86 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..75b2d16 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..c4df70d Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..6a84f41 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..d0e1f58 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/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/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/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/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..64cdbc1 --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,47 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Agente Ventas + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + Agente Ventas SIGMAC + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/lib/app.dart b/lib/app.dart new file mode 100644 index 0000000..3bd243c --- /dev/null +++ b/lib/app.dart @@ -0,0 +1,62 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'providers/app_provider.dart'; +import 'theme/app_theme.dart'; +import 'screens/login/login_screen.dart'; +import 'screens/main_shell.dart'; + +class PedidosApp extends StatelessWidget { + final GlobalKey navigatorKey; + + const PedidosApp({Key? key, required this.navigatorKey}) : super(key: key); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Agente Ventas SIGMAC', + debugShowCheckedModeBanner: false, + theme: AppTheme.light, + navigatorKey: navigatorKey, + home: Consumer( + builder: (_, provider, __) { + if (provider.loading) return const _LoadingScreen(); + return provider.isLoggedIn ? const MainShell() : const LoginScreen(); + }, + ), + ); + } +} + +class _LoadingScreen extends StatelessWidget { + const _LoadingScreen({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppTheme.primaryColor, + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(22), + child: Image.asset('assets/icon/icon.png', width: 80, height: 80), + ), + const SizedBox(height: 20), + const Text( + 'Agente Ventas', + style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold, color: Colors.white), + ), + const SizedBox(height: 4), + Text( + 'by SIGMAC', + style: TextStyle(fontSize: 12, color: Colors.white.withOpacity(0.6), letterSpacing: 2.0), + ), + const SizedBox(height: 40), + const Text('Cargando datos...', style: TextStyle(color: Colors.white70, fontSize: 13)), + ], + ), + ), + ); + } +} diff --git a/lib/data/mock_data.dart b/lib/data/mock_data.dart new file mode 100644 index 0000000..c4b25a0 --- /dev/null +++ b/lib/data/mock_data.dart @@ -0,0 +1,462 @@ +import '../models/vendedor.dart'; +import '../models/cliente.dart'; +import '../models/producto.dart'; +import '../models/pedido.dart'; +import '../models/item_pedido.dart'; +import '../models/parada_ruta.dart'; +import '../models/ruta.dart'; + +class MockData { + // ── Vendedor ────────────────────────────────────────────────── + static const vendedor = Vendedor( + id: 'v1', + nombre: 'Roberto Vargas', + email: 'admin@telcotronics.com', + telefono: '+591 76123456', + zona: 'La Paz – Centro y Zona Sur', + avatarInitials: 'RV', + ); + + // ── Clientes ────────────────────────────────────────────────── + static final clientes = [ + const Cliente( + id: 'c1', + nombre: 'TechZone Bolivia', + razonSocial: 'TechZone Bolivia S.R.L.', + direccion: 'Av. 16 de Julio 1890, El Prado, La Paz', + telefono: '+591 22310456', + nit: '1023456789', + lat: -16.495, + lng: -68.133, + categoria: 'Mayorista', + ), + const Cliente( + id: 'c2', + nombre: 'InfoSystems La Paz', + razonSocial: 'InfoSystems Bolivia S.A.', + direccion: 'Calle Comercio 1245, Piso 3, La Paz', + telefono: '+591 22451230', + nit: '2034567891', + lat: -16.498, + lng: -68.130, + categoria: 'Distribuidor', + ), + const Cliente( + id: 'c3', + nombre: 'CyberShop Sopocachi', + razonSocial: 'Miguel Ángel Ramos', + direccion: 'Av. 6 de Agosto 2378, Sopocachi', + telefono: '+591 71234890', + nit: '3045678912', + lat: -16.507, + lng: -68.121, + categoria: 'Minorista', + ), + const Cliente( + id: 'c4', + nombre: 'Hotel Presidente La Paz', + razonSocial: 'Hoteles Presidente Bolivia S.A.', + direccion: 'Calle Potosí 920, Centro, La Paz', + telefono: '+591 22406666', + nit: '4056789123', + lat: -16.500, + lng: -68.128, + categoria: 'Empresa', + ), + const Cliente( + id: 'c5', + nombre: 'Colegio Técnico INFOCAL', + razonSocial: 'INFOCAL La Paz', + direccion: 'Av. Arce 2081, Miraflores, La Paz', + telefono: '+591 22430012', + nit: '5067891234', + lat: -16.514, + lng: -68.115, + categoria: 'Institución', + ), + const Cliente( + id: 'c6', + nombre: 'DataCenter Andino', + razonSocial: 'Andino Cloud Solutions S.R.L.', + direccion: 'Av. Hernando Siles 5635, Obrajes', + telefono: '+591 22782200', + nit: '6078912345', + lat: -16.521, + lng: -68.118, + categoria: 'Empresa', + ), + const Cliente( + id: 'c7', + nombre: 'Electrónica Calacoto', + razonSocial: 'Electrónica Calacoto S.R.L.', + direccion: 'Calle 21 de Calacoto 8251, Zona Sur', + telefono: '+591 22771890', + nit: '7089123456', + lat: -16.531, + lng: -68.107, + categoria: 'Minorista', + ), + const Cliente( + id: 'c8', + nombre: 'Gobernación Dpto. La Paz', + razonSocial: 'Gobernación del Departamento de La Paz', + direccion: 'Av. Mariscal Santa Cruz, Edif. Gobernación', + telefono: '+591 22204500', + nit: '1000000001', + lat: -16.501, + lng: -68.134, + categoria: 'Gobierno', + ), + ]; + + // ── Productos ───────────────────────────────────────────────── + static final productos = [ + // Redes & Conectividad + const Producto( + id: 'p01', sku: 'RED001', + nombre: 'Router WiFi TP-Link Archer AX73', + descripcion: 'Router AX5400 Wi-Fi 6, doble banda, 6 antenas, ideal oficinas y hogares', + categoria: 'Redes & Conectividad', + precio: 1250.00, precioMayorista: 1080.00, + unidad: 'unidad', stock: 24, emoji: '📡', + ), + const Producto( + id: 'p02', sku: 'RED002', + nombre: 'Switch Cisco SG350 24 puertos', + descripcion: 'Switch gestionable 24 puertos Gigabit, ideal redes empresariales', + categoria: 'Redes & Conectividad', + precio: 4800.00, precioMayorista: 4200.00, + unidad: 'unidad', stock: 8, emoji: '🔀', + ), + const Producto( + id: 'p03', sku: 'RED003', + nombre: 'Access Point Ubiquiti UniFi U6 Pro', + descripcion: 'AP Wi-Fi 6 de alto rendimiento, cobertura hasta 300m², PoE', + categoria: 'Redes & Conectividad', + precio: 2100.00, precioMayorista: 1820.00, + unidad: 'unidad', stock: 15, emoji: '📶', + ), + const Producto( + id: 'p04', sku: 'RED004', + nombre: 'Cable UTP Cat6 Rollo 305m', + descripcion: 'Cable de red categoría 6, 305 metros, color gris, certificado', + categoria: 'Redes & Conectividad', + precio: 680.00, precioMayorista: 580.00, + unidad: 'rollo', stock: 30, emoji: '🔌', + ), + const Producto( + id: 'p05', sku: 'RED005', + nombre: 'Patch Panel 24p Cat6 AMP', + descripcion: 'Panel de parcheo 24 puertos, categoría 6, montaje en rack 1U', + categoria: 'Redes & Conectividad', + precio: 540.00, precioMayorista: 460.00, + unidad: 'unidad', stock: 12, emoji: '🗄️', + ), + const Producto( + id: 'p06', sku: 'RED006', + nombre: 'Firewall Fortinet FortiGate 60F', + descripcion: 'Firewall NGFW 10 Gbps, VPN, protección avanzada de amenazas', + categoria: 'Redes & Conectividad', + precio: 8900.00, precioMayorista: 7800.00, + unidad: 'unidad', stock: 5, emoji: '🛡️', + ), + + // Telefonía & Móviles + const Producto( + id: 'p07', sku: 'TEL001', + nombre: 'Smartphone Samsung Galaxy A55 5G', + descripcion: '6.6" AMOLED, 8GB RAM, 256GB, cámara 50MP, 5G, batería 5000mAh', + categoria: 'Telefonía & Móviles', + precio: 3200.00, precioMayorista: 2850.00, + unidad: 'unidad', stock: 20, emoji: '📱', + ), + const Producto( + id: 'p08', sku: 'TEL002', + nombre: 'Tablet Lenovo Tab M11 LTE', + descripcion: '11" FHD, 4GB RAM, 128GB, Android 13, SIM 4G, lápiz incluido', + categoria: 'Telefonía & Móviles', + precio: 2400.00, precioMayorista: 2100.00, + unidad: 'unidad', stock: 12, emoji: '📟', + ), + const Producto( + id: 'p09', sku: 'TEL003', + nombre: 'Teléfono IP Yealink T46U', + descripcion: 'Teléfono VoIP color, 16 líneas SIP, USB, PoE, pantalla 4.3"', + categoria: 'Telefonía & Móviles', + precio: 1450.00, precioMayorista: 1240.00, + unidad: 'unidad', stock: 18, emoji: '☎️', + ), + const Producto( + id: 'p10', sku: 'TEL004', + nombre: 'Central IP 3CX Licencia 25 ext.', + descripcion: 'Licencia anual central telefónica IP 3CX, hasta 25 extensiones', + categoria: 'Telefonía & Móviles', + precio: 5600.00, precioMayorista: 4900.00, + unidad: 'licencia', stock: 10, emoji: '🏢', + ), + + // Cómputo & Periféricos + const Producto( + id: 'p11', sku: 'COM001', + nombre: 'Laptop HP ProBook 450 G10', + descripcion: 'Intel Core i7-13ª gen, 16GB RAM, SSD 512GB, 15.6" FHD, Windows 11 Pro', + categoria: 'Cómputo & Periféricos', + precio: 9800.00, precioMayorista: 8700.00, + unidad: 'unidad', stock: 10, emoji: '💻', + ), + const Producto( + id: 'p12', sku: 'COM002', + nombre: 'Monitor LG 27" 4K UHD IPS', + descripcion: 'Monitor 27 pulgadas 4K, panel IPS, USB-C, HDR10, 60Hz', + categoria: 'Cómputo & Periféricos', + precio: 3600.00, precioMayorista: 3100.00, + unidad: 'unidad', stock: 14, emoji: '🖥️', + ), + const Producto( + id: 'p13', sku: 'COM003', + nombre: 'UPS APC 1500VA Smart', + descripcion: 'UPS línea interactiva 1500VA/900W, 8 tomas, pantalla LCD, USB', + categoria: 'Cómputo & Periféricos', + precio: 2200.00, precioMayorista: 1900.00, + unidad: 'unidad', stock: 16, emoji: '🔋', + ), + const Producto( + id: 'p14', sku: 'COM004', + nombre: 'Impresora HP LaserJet Pro M404n', + descripcion: 'Impresora láser monocromática, 38ppm, red Ethernet, duplex automático', + categoria: 'Cómputo & Periféricos', + precio: 3100.00, precioMayorista: 2700.00, + unidad: 'unidad', stock: 9, emoji: '🖨️', + ), + const Producto( + id: 'p15', sku: 'COM005', + nombre: 'Disco Duro Externo Seagate 2TB', + descripcion: 'HDD externo 2TB USB 3.0, compatible Windows/Mac/Linux', + categoria: 'Cómputo & Periféricos', + precio: 580.00, precioMayorista: 490.00, + unidad: 'unidad', stock: 35, emoji: '💾', + ), + + // Seguridad & Vigilancia + const Producto( + id: 'p16', sku: 'SEG001', + nombre: 'Cámara IP Hikvision 4MP Domo', + descripcion: 'Cámara IP domo 4MP, IR 30m, PoE, IP67, detección de movimiento IA', + categoria: 'Seguridad & Vigilancia', + precio: 980.00, precioMayorista: 840.00, + unidad: 'unidad', stock: 28, emoji: '📷', + ), + const Producto( + id: 'p17', sku: 'SEG002', + nombre: 'NVR Dahua 16 canales 4K', + descripcion: 'Grabador de red 16 canales, resolución 4K, HDMI, 2 bahías HDD, PoE', + categoria: 'Seguridad & Vigilancia', + precio: 2800.00, precioMayorista: 2400.00, + unidad: 'unidad', stock: 7, emoji: '🎥', + ), + const Producto( + id: 'p18', sku: 'SEG003', + nombre: 'Control de Acceso ZKTeco SF300', + descripcion: 'Control de acceso biométrico facial y huella, 3000 usuarios, TCP/IP', + categoria: 'Seguridad & Vigilancia', + precio: 1680.00, precioMayorista: 1450.00, + unidad: 'unidad', stock: 11, emoji: '🔒', + ), + const Producto( + id: 'p19', sku: 'SEG004', + nombre: 'Disco Duro WD Purple 4TB Surveillance', + descripcion: 'HDD diseñado para videovigilancia, funcionamiento 24/7, SATA 3', + categoria: 'Seguridad & Vigilancia', + precio: 760.00, precioMayorista: 650.00, + unidad: 'unidad', stock: 22, emoji: '🗂️', + ), + + // Servicios Telcotronics + const Producto( + id: 'p20', sku: 'SRV001', + nombre: 'Instalación de Red Estructurada', + descripcion: 'Servicio de instalación y certificación de red categoría 6 por punto', + categoria: 'Servicios', + precio: 350.00, precioMayorista: 300.00, + unidad: 'punto', stock: 999, emoji: '🔧', + ), + const Producto( + id: 'p21', sku: 'SRV002', + nombre: 'Soporte Técnico Presencial (hora)', + descripcion: 'Visita técnica presencial, diagnóstico y resolución de problemas', + categoria: 'Servicios', + precio: 280.00, precioMayorista: 240.00, + unidad: 'hora', stock: 999, emoji: '🛠️', + ), + const Producto( + id: 'p22', sku: 'SRV003', + nombre: 'Contrato Mantenimiento Anual Redes', + descripcion: 'Mantenimiento preventivo trimestral de infraestructura de red', + categoria: 'Servicios', + precio: 4200.00, precioMayorista: 3600.00, + unidad: 'contrato', stock: 999, emoji: '📋', + ), + const Producto( + id: 'p23', sku: 'SRV004', + nombre: 'Configuración Firewall / VPN', + descripcion: 'Servicio de configuración, políticas de seguridad y túneles VPN', + categoria: 'Servicios', + precio: 1200.00, precioMayorista: 1000.00, + unidad: 'servicio', stock: 999, emoji: '⚙️', + ), + const Producto( + id: 'p24', sku: 'SRV005', + nombre: 'Instalación CCTV (cámara)', + descripcion: 'Instalación y configuración de cámara IP incluye cableado hasta 30m', + categoria: 'Servicios', + precio: 420.00, precioMayorista: 360.00, + unidad: 'cámara', stock: 999, emoji: '📹', + ), + ]; + + // ── Ruta del día ────────────────────────────────────────────── + static List _buildParadas() { + return [ + ParadaRuta( + id: 'pr1', cliente: clientes[0], orden: 1, + estado: EstadoParada.visitado, horaEstimada: '08:30', horaVisita: '08:42', + notasVisita: 'Firmó pedido. Solicita cotización para 10 AP adicionales.', + ), + ParadaRuta( + id: 'pr2', cliente: clientes[2], orden: 2, + estado: EstadoParada.visitado, horaEstimada: '09:30', horaVisita: '09:28', + ), + ParadaRuta( + id: 'pr3', cliente: clientes[3], orden: 3, + estado: EstadoParada.pendiente, horaEstimada: '10:45', + ), + ParadaRuta( + id: 'pr4', cliente: clientes[5], orden: 4, + estado: EstadoParada.pendiente, horaEstimada: '12:00', + ), + ParadaRuta( + id: 'pr5', cliente: clientes[1], orden: 5, + estado: EstadoParada.pendiente, horaEstimada: '14:00', + ), + ParadaRuta( + id: 'pr6', cliente: clientes[6], orden: 6, + estado: EstadoParada.pendiente, horaEstimada: '16:00', + ), + ]; + } + + static Ruta buildRuta() => Ruta( + id: 'r1', + nombre: 'Ruta Centro & Zona Sur', + zona: 'Centro – Sopocachi – Miraflores – Obrajes – Calacoto', + paradas: _buildParadas(), + fecha: DateTime.now(), + ); + + // ── Pedidos ─────────────────────────────────────────────────── + static List buildPedidos() { + final p = productos; + return [ + // Pedido entregado hoy — TechZone + Pedido( + id: 'TTC-0041', + cliente: clientes[0], + estado: EstadoPedido.entregado, + fecha: DateTime.now().subtract(const Duration(hours: 3)), + notas: 'Entrega urgente. Factura a nombre de empresa.', + firmaBase64: 'signed', + items: [ + ItemPedido(producto: p[0], cantidad: 5, precioUnitario: p[0].precioMayorista), + ItemPedido(producto: p[2], cantidad: 4, precioUnitario: p[2].precioMayorista), + ItemPedido(producto: p[3], cantidad: 3, precioUnitario: p[3].precioMayorista), + ], + ), + // Pedido confirmado hoy — CyberShop + Pedido( + id: 'TTC-0042', + cliente: clientes[2], + estado: EstadoPedido.confirmado, + fecha: DateTime.now().subtract(const Duration(hours: 1)), + notas: 'Recoger en tienda', + firmaBase64: 'signed', + items: [ + ItemPedido(producto: p[6], cantidad: 3, precioUnitario: p[6].precio), + ItemPedido(producto: p[14], cantidad: 4, precioUnitario: p[14].precio), + ItemPedido(producto: p[15], cantidad: 2, precioUnitario: p[15].precio), + ], + ), + // Pedido pendiente — Hotel Presidente + Pedido( + id: 'TTC-0043', + cliente: clientes[3], + estado: EstadoPedido.pendiente, + fecha: DateTime.now().subtract(const Duration(days: 1)), + notas: 'Instalación CCTV piso 1 al 5. Coordinar con Jefe de Mantenimiento.', + items: [ + ItemPedido(producto: p[15], cantidad: 12, precioUnitario: p[15].precioMayorista), + ItemPedido(producto: p[16], cantidad: 2, precioUnitario: p[16].precioMayorista), + ItemPedido(producto: p[18], cantidad: 1, precioUnitario: p[18].precioMayorista), + ItemPedido(producto: p[23], cantidad: 12, precioUnitario: p[23].precioMayorista), + ], + ), + // Pedido pendiente — DataCenter Andino + Pedido( + id: 'TTC-0044', + cliente: clientes[5], + estado: EstadoPedido.pendiente, + fecha: DateTime.now().subtract(const Duration(days: 1, hours: 4)), + notas: 'Ampliar infraestructura sala de servidores. Requiere rack de 42U.', + items: [ + ItemPedido(producto: p[1], cantidad: 2, precioUnitario: p[1].precioMayorista), + ItemPedido(producto: p[4], cantidad: 4, precioUnitario: p[4].precioMayorista), + ItemPedido(producto: p[5], cantidad: 1, precioUnitario: p[5].precioMayorista), + ItemPedido(producto: p[12], cantidad: 4, precioUnitario: p[12].precioMayorista), + ItemPedido(producto: p[21], cantidad: 8, precioUnitario: p[21].precioMayorista), + ], + ), + // Pedido pendiente — InfoSystems + Pedido( + id: 'TTC-0045', + cliente: clientes[1], + estado: EstadoPedido.pendiente, + fecha: DateTime.now().subtract(const Duration(days: 2)), + notas: 'Pedido trimestral de reposición. Pago 30 días.', + items: [ + ItemPedido(producto: p[0], cantidad: 10, precioUnitario: p[0].precioMayorista), + ItemPedido(producto: p[6], cantidad: 8, precioUnitario: p[6].precioMayorista), + ItemPedido(producto: p[8], cantidad: 6, precioUnitario: p[8].precioMayorista), + ItemPedido(producto: p[13], cantidad: 5, precioUnitario: p[13].precioMayorista), + ], + ), + // Pedido confirmado — INFOCAL + Pedido( + id: 'TTC-0046', + cliente: clientes[4], + estado: EstadoPedido.confirmado, + fecha: DateTime.now().subtract(const Duration(days: 3)), + notas: 'Equipamiento laboratorio de redes. Licitación Ref. INFOCAL-2024-018.', + firmaBase64: 'signed', + items: [ + ItemPedido(producto: p[1], cantidad: 1, precioUnitario: p[1].precioMayorista), + ItemPedido(producto: p[2], cantidad: 6, precioUnitario: p[2].precioMayorista), + ItemPedido(producto: p[3], cantidad: 5, precioUnitario: p[3].precioMayorista), + ItemPedido(producto: p[4], cantidad: 2, precioUnitario: p[4].precioMayorista), + ItemPedido(producto: p[20], cantidad: 48, precioUnitario: p[20].precioMayorista), + ], + ), + // Pedido cancelado — Gobernación + Pedido( + id: 'TTC-0040', + cliente: clientes[7], + estado: EstadoPedido.cancelado, + fecha: DateTime.now().subtract(const Duration(days: 4)), + notas: 'Proceso licitatorio suspendido por cambio de presupuesto.', + items: [ + ItemPedido(producto: p[10], cantidad: 20, precioUnitario: p[10].precioMayorista), + ItemPedido(producto: p[11], cantidad: 20, precioUnitario: p[11].precioMayorista), + ItemPedido(producto: p[22], cantidad: 1, precioUnitario: p[22].precioMayorista), + ], + ), + ]; + } +} diff --git a/lib/database/database_helper.dart b/lib/database/database_helper.dart new file mode 100644 index 0000000..330bb05 --- /dev/null +++ b/lib/database/database_helper.dart @@ -0,0 +1,359 @@ +import 'dart:io' show Platform; +import 'package:path/path.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +import '../models/vendedor.dart'; +import '../models/cliente.dart'; +import '../models/producto.dart'; +import '../models/pedido.dart'; +import '../models/item_pedido.dart'; +import '../models/ruta.dart'; +import '../models/parada_ruta.dart'; + +class DatabaseHelper { + static final DatabaseHelper _instance = DatabaseHelper._(); + factory DatabaseHelper() => _instance; + DatabaseHelper._(); + + static Database? _db; + + Future get database async { + _db ??= await _initDB(); + return _db!; + } + + Future _initDB() async { + if (Platform.isLinux || Platform.isWindows || Platform.isMacOS) { + sqfliteFfiInit(); + final dbPath = await databaseFactoryFfi.getDatabasesPath(); + final path = join(dbPath, 'telcotronics.db'); + return databaseFactoryFfi.openDatabase( + path, + options: OpenDatabaseOptions(version: 1, onCreate: _createTables), + ); + } + final dbPath = await getDatabasesPath(); + final path = join(dbPath, 'telcotronics.db'); + return openDatabase(path, version: 1, onCreate: _createTables); + } + + Future _createTables(Database db, int version) async { + await db.execute(''' + CREATE TABLE usuarios ( + id TEXT PRIMARY KEY, + nombre TEXT NOT NULL, + email TEXT NOT NULL UNIQUE, + password TEXT NOT NULL, + telefono TEXT, + zona TEXT, + avatar_initials TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE clientes ( + id TEXT PRIMARY KEY, + nombre TEXT NOT NULL, + razon_social TEXT, + direccion TEXT, + telefono TEXT, + nit TEXT, + lat REAL DEFAULT 0, + lng REAL DEFAULT 0, + categoria TEXT DEFAULT 'Minorista' + ) + '''); + + await db.execute(''' + CREATE TABLE productos ( + id TEXT PRIMARY KEY, + sku TEXT UNIQUE NOT NULL, + nombre TEXT NOT NULL, + descripcion TEXT, + categoria TEXT, + precio REAL NOT NULL, + precio_mayorista REAL NOT NULL, + unidad TEXT DEFAULT 'unidad', + stock INTEGER DEFAULT 0, + emoji TEXT DEFAULT '📦' + ) + '''); + + await db.execute(''' + CREATE TABLE rutas ( + id TEXT PRIMARY KEY, + nombre TEXT NOT NULL, + zona TEXT, + fecha TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE paradas_ruta ( + id TEXT PRIMARY KEY, + ruta_id TEXT NOT NULL, + cliente_id TEXT NOT NULL, + orden INTEGER NOT NULL, + estado TEXT NOT NULL DEFAULT 'pendiente', + hora_estimada TEXT, + hora_visita TEXT, + notas_visita TEXT, + FOREIGN KEY (ruta_id) REFERENCES rutas(id) ON DELETE CASCADE, + FOREIGN KEY (cliente_id) REFERENCES clientes(id) + ) + '''); + + await db.execute(''' + CREATE TABLE pedidos ( + id TEXT PRIMARY KEY, + cliente_id TEXT NOT NULL, + estado TEXT NOT NULL DEFAULT 'pendiente', + fecha TEXT NOT NULL, + notas TEXT, + firma_base64 TEXT, + FOREIGN KEY (cliente_id) REFERENCES clientes(id) + ) + '''); + + await db.execute(''' + CREATE TABLE items_pedido ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + pedido_id TEXT NOT NULL, + producto_id TEXT NOT NULL, + cantidad INTEGER NOT NULL, + precio_unitario REAL NOT NULL, + FOREIGN KEY (pedido_id) REFERENCES pedidos(id) ON DELETE CASCADE, + FOREIGN KEY (producto_id) REFERENCES productos(id) + ) + '''); + } + + // ── Usuarios ──────────────────────────────────────────────── + + Future insertUsuario(Vendedor v, String password) async { + final db = await database; + await db.insert('usuarios', {...v.toMap(), 'password': password}, + conflictAlgorithm: ConflictAlgorithm.ignore); + } + + Future?> loginUsuario(String email, String password) async { + final db = await database; + final rows = await db.query('usuarios', + where: 'email = ? AND password = ?', whereArgs: [email, password]); + return rows.isEmpty ? null : rows.first; + } + + Future getVendedor(String id) async { + final db = await database; + final rows = await db.query('usuarios', where: 'id = ?', whereArgs: [id]); + return rows.isEmpty ? null : Vendedor.fromMap(rows.first); + } + + // ── Clientes ──────────────────────────────────────────────── + + Future> getClientes() async { + final db = await database; + final rows = await db.query('clientes', orderBy: 'nombre ASC'); + return rows.map(Cliente.fromMap).toList(); + } + + Future insertCliente(Cliente c) async { + final db = await database; + await db.insert('clientes', c.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace); + } + + Future updateCliente(Cliente c) async { + final db = await database; + await db.update('clientes', c.toMap(), where: 'id = ?', whereArgs: [c.id]); + } + + Future deleteCliente(String id) async { + final db = await database; + await db.delete('clientes', where: 'id = ?', whereArgs: [id]); + } + + // ── Productos ──────────────────────────────────────────────── + + Future> getProductos() async { + final db = await database; + final rows = await db.query('productos', orderBy: 'categoria ASC, nombre ASC'); + return rows.map(Producto.fromMap).toList(); + } + + Future insertProducto(Producto p) async { + final db = await database; + await db.insert('productos', p.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace); + } + + Future updateProducto(Producto p) async { + final db = await database; + await db.update('productos', p.toMap(), where: 'id = ?', whereArgs: [p.id]); + } + + Future updateStock(String productoId, int nuevoStock) async { + final db = await database; + await db.update('productos', {'stock': nuevoStock}, + where: 'id = ?', whereArgs: [productoId]); + } + + // ── Rutas ──────────────────────────────────────────────────── + + Future getRutaIdHoy() async { + final db = await database; + final hoy = DateTime.now().toIso8601String().substring(0, 10); + final rows = await db.query('rutas', + where: "fecha LIKE ?", whereArgs: ['$hoy%']); + return rows.isEmpty ? null : rows.first['id'] as String; + } + + Future getRutaConParadas( + String rutaId, Map clientesMap) async { + final db = await database; + final rutaRows = await db.query('rutas', where: 'id = ?', whereArgs: [rutaId]); + if (rutaRows.isEmpty) return null; + final r = rutaRows.first; + + final paradaRows = await db.query('paradas_ruta', + where: 'ruta_id = ?', whereArgs: [rutaId], orderBy: 'orden ASC'); + + final paradas = paradaRows.map((row) { + final cliente = clientesMap[row['cliente_id'] as String]; + if (cliente == null) return null; + return ParadaRuta( + id: row['id'] as String, + cliente: cliente, + orden: row['orden'] as int, + estado: EstadoParadaExt.fromString(row['estado'] as String), + horaEstimada: row['hora_estimada'] as String? ?? '', + horaVisita: row['hora_visita'] as String?, + notasVisita: row['notas_visita'] as String?, + ); + }).whereType().toList(); + + return Ruta( + id: r['id'] as String, + nombre: r['nombre'] as String, + zona: r['zona'] as String? ?? '', + paradas: paradas, + fecha: DateTime.parse(r['fecha'] as String), + ); + } + + Future insertRuta(Ruta ruta) async { + final db = await database; + await db.insert('rutas', ruta.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace); + return ruta.id; + } + + Future insertParada(ParadaRuta parada, String rutaId) async { + final db = await database; + await db.insert('paradas_ruta', parada.toMap(rutaId), + conflictAlgorithm: ConflictAlgorithm.replace); + } + + Future updateParadaEstado( + String paradaId, String estado, String? horaVisita) async { + final db = await database; + await db.update( + 'paradas_ruta', + {'estado': estado, 'hora_visita': horaVisita}, + where: 'id = ?', + whereArgs: [paradaId], + ); + } + + Future deleteParada(String paradaId) async { + final db = await database; + await db.delete('paradas_ruta', where: 'id = ?', whereArgs: [paradaId]); + } + + Future reordenarParadas(List paradas, String rutaId) async { + final db = await database; + final batch = db.batch(); + for (int i = 0; i < paradas.length; i++) { + batch.update('paradas_ruta', {'orden': i + 1}, + where: 'id = ?', whereArgs: [paradas[i].id]); + } + await batch.commit(noResult: true); + } + + // ── Pedidos ───────────────────────────────────────────────── + + Future> getPedidos( + Map clientesMap, Map productosMap) async { + final db = await database; + final pedidoRows = await db.query('pedidos', orderBy: 'fecha DESC'); + + final pedidos = []; + for (final row in pedidoRows) { + final cliente = clientesMap[row['cliente_id'] as String]; + if (cliente == null) continue; + + final itemRows = await db.query('items_pedido', + where: 'pedido_id = ?', whereArgs: [row['id']]); + + final items = itemRows.map((ir) { + final producto = productosMap[ir['producto_id'] as String]; + if (producto == null) return null; + return ItemPedido( + dbId: ir['id'] as int?, + producto: producto, + cantidad: ir['cantidad'] as int, + precioUnitario: (ir['precio_unitario'] as num).toDouble(), + ); + }).whereType().toList(); + + pedidos.add(Pedido( + id: row['id'] as String, + cliente: cliente, + estado: EstadoPedidoExt.fromString(row['estado'] as String), + fecha: DateTime.parse(row['fecha'] as String), + notas: row['notas'] as String? ?? '', + firmaBase64: row['firma_base64'] as String?, + items: items, + )); + } + return pedidos; + } + + Future insertPedido(Pedido pedido) async { + final db = await database; + await db.insert('pedidos', pedido.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace); + for (final item in pedido.items) { + await db.insert('items_pedido', item.toMap(pedido.id), + conflictAlgorithm: ConflictAlgorithm.replace); + } + } + + Future updateEstadoPedido(String pedidoId, String estado) async { + final db = await database; + await db.update('pedidos', {'estado': estado}, + where: 'id = ?', whereArgs: [pedidoId]); + } + + Future updateFirmaPedido(String pedidoId, String firma) async { + final db = await database; + await db.update('pedidos', {'firma_base64': firma, 'estado': 'confirmado'}, + where: 'id = ?', whereArgs: [pedidoId]); + } + + Future deletePedido(String pedidoId) async { + final db = await database; + await db.delete('pedidos', where: 'id = ?', whereArgs: [pedidoId]); + } + + // ── Utilidades ─────────────────────────────────────────────── + + Future isSeeded() async { + final db = await database; + final rows = await db.query('productos', limit: 1); + return rows.isNotEmpty; + } + + Future close() async => (await database).close(); +} diff --git a/lib/database/db_seeder.dart b/lib/database/db_seeder.dart new file mode 100644 index 0000000..84e5779 --- /dev/null +++ b/lib/database/db_seeder.dart @@ -0,0 +1,35 @@ +import 'database_helper.dart'; +import '../data/mock_data.dart'; + +class DbSeeder { + final DatabaseHelper _db; + DbSeeder(this._db); + + Future seed() async { + // Guardar usuario admin + await _db.insertUsuario(MockData.vendedor, 'Microbot%'); + + // Clientes + for (final c in MockData.clientes) { + await _db.insertCliente(c); + } + + // Productos + for (final p in MockData.productos) { + await _db.insertProducto(p); + } + + // Ruta del día + final ruta = MockData.buildRuta(); + await _db.insertRuta(ruta); + for (final parada in ruta.paradas) { + await _db.insertParada(parada, ruta.id); + } + + // Pedidos históricos + final pedidos = MockData.buildPedidos(); + for (final pedido in pedidos) { + await _db.insertPedido(pedido); + } + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..34afb3d --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,32 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:intl/date_symbol_data_local.dart'; +import 'package:provider/provider.dart'; +import 'app.dart'; +import 'providers/app_provider.dart'; +import 'services/notification_service.dart'; + +final _navigatorKey = GlobalKey(); + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + await initializeDateFormatting('es', null); + SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle( + statusBarColor: Colors.transparent, + statusBarIconBrightness: Brightness.light, + )); + + final notifService = NotificationService(navigatorKey: _navigatorKey); + + runApp( + MultiProvider( + providers: [ + ChangeNotifierProvider( + create: (_) => AppProvider(notifService: notifService), + ), + ChangeNotifierProvider.value(value: notifService), + ], + child: PedidosApp(navigatorKey: _navigatorKey), + ), + ); +} diff --git a/lib/models/cliente.dart b/lib/models/cliente.dart new file mode 100644 index 0000000..ab33b67 --- /dev/null +++ b/lib/models/cliente.dart @@ -0,0 +1,60 @@ +class Cliente { + final String id; + final String nombre; + final String razonSocial; + final String direccion; + final String telefono; + final String nit; + final double lat; + final double lng; + final String categoria; + + const Cliente({ + required this.id, + required this.nombre, + required this.razonSocial, + required this.direccion, + required this.telefono, + required this.nit, + required this.lat, + required this.lng, + required this.categoria, + }); + + Map toMap() => { + 'id': id, + 'nombre': nombre, + 'razon_social': razonSocial, + 'direccion': direccion, + 'telefono': telefono, + 'nit': nit, + 'lat': lat, + 'lng': lng, + 'categoria': categoria, + }; + + factory Cliente.fromMap(Map m) => Cliente( + id: m['id'] as String, + nombre: m['nombre'] as String, + razonSocial: m['razon_social'] as String? ?? '', + direccion: m['direccion'] as String? ?? '', + telefono: m['telefono'] as String? ?? '', + nit: m['nit'] as String? ?? '', + lat: (m['lat'] as num?)?.toDouble() ?? 0.0, + lng: (m['lng'] as num?)?.toDouble() ?? 0.0, + categoria: m['categoria'] as String? ?? 'Minorista', + ); + + Cliente copyWith({ + String? nombre, String? razonSocial, String? direccion, + String? telefono, String? nit, String? categoria, + }) => Cliente( + id: id, lat: lat, lng: lng, + nombre: nombre ?? this.nombre, + razonSocial: razonSocial ?? this.razonSocial, + direccion: direccion ?? this.direccion, + telefono: telefono ?? this.telefono, + nit: nit ?? this.nit, + categoria: categoria ?? this.categoria, + ); +} diff --git a/lib/models/item_pedido.dart b/lib/models/item_pedido.dart new file mode 100644 index 0000000..d32be2a --- /dev/null +++ b/lib/models/item_pedido.dart @@ -0,0 +1,25 @@ +import 'producto.dart'; + +class ItemPedido { + final int? dbId; + final Producto producto; + int cantidad; + double precioUnitario; + + ItemPedido({ + this.dbId, + required this.producto, + required this.cantidad, + required this.precioUnitario, + }); + + double get subtotal => cantidad * precioUnitario; + + Map toMap(String pedidoId) => { + if (dbId != null) 'id': dbId, + 'pedido_id': pedidoId, + 'producto_id': producto.id, + 'cantidad': cantidad, + 'precio_unitario': precioUnitario, + }; +} diff --git a/lib/models/notificacion.dart b/lib/models/notificacion.dart new file mode 100644 index 0000000..223f03b --- /dev/null +++ b/lib/models/notificacion.dart @@ -0,0 +1,69 @@ +import 'package:flutter/material.dart'; + +enum TipoNotificacion { + pedidoConfirmado, + pedidoEntregado, + paradaProxima, + stockBajo, + metaVentas, + recordatorio, + alerta, +} + +extension TipoNotificacionExt on TipoNotificacion { + String get label { + switch (this) { + case TipoNotificacion.pedidoConfirmado: return 'Pedido confirmado'; + case TipoNotificacion.pedidoEntregado: return 'Pedido entregado'; + case TipoNotificacion.paradaProxima: return 'Próxima parada'; + case TipoNotificacion.stockBajo: return 'Stock bajo'; + case TipoNotificacion.metaVentas: return 'Meta de ventas'; + case TipoNotificacion.recordatorio: return 'Recordatorio'; + case TipoNotificacion.alerta: return 'Alerta'; + } + } + + IconData get icono { + switch (this) { + case TipoNotificacion.pedidoConfirmado: return Icons.receipt_long; + case TipoNotificacion.pedidoEntregado: return Icons.local_shipping; + case TipoNotificacion.paradaProxima: return Icons.location_on; + case TipoNotificacion.stockBajo: return Icons.inventory_2; + case TipoNotificacion.metaVentas: return Icons.trending_up; + case TipoNotificacion.recordatorio: return Icons.alarm; + case TipoNotificacion.alerta: return Icons.warning_amber; + } + } + + Color get color { + switch (this) { + case TipoNotificacion.pedidoConfirmado: return const Color(0xFF16A34A); + case TipoNotificacion.pedidoEntregado: return const Color(0xFF0891B2); + case TipoNotificacion.paradaProxima: return const Color(0xFF2563EB); + case TipoNotificacion.stockBajo: return const Color(0xFFD97706); + case TipoNotificacion.metaVentas: return const Color(0xFF7C3AED); + case TipoNotificacion.recordatorio: return const Color(0xFF0891B2); + case TipoNotificacion.alerta: return const Color(0xFFDC2626); + } + } +} + +class Notificacion { + final String id; + final TipoNotificacion tipo; + final String titulo; + final String cuerpo; + final DateTime fecha; + bool leida; + final String? accionId; + + Notificacion({ + required this.id, + required this.tipo, + required this.titulo, + required this.cuerpo, + required this.fecha, + this.leida = false, + this.accionId, + }); +} diff --git a/lib/models/parada_ruta.dart b/lib/models/parada_ruta.dart new file mode 100644 index 0000000..0ed7820 --- /dev/null +++ b/lib/models/parada_ruta.dart @@ -0,0 +1,52 @@ +import 'cliente.dart'; + +enum EstadoParada { pendiente, visitado, saltado } + +extension EstadoParadaExt on EstadoParada { + String get value { + switch (this) { + case EstadoParada.visitado: return 'visitado'; + case EstadoParada.saltado: return 'saltado'; + default: return 'pendiente'; + } + } + + static EstadoParada fromString(String s) { + switch (s) { + case 'visitado': return EstadoParada.visitado; + case 'saltado': return EstadoParada.saltado; + default: return EstadoParada.pendiente; + } + } +} + +class ParadaRuta { + final String id; + final Cliente cliente; + final int orden; + EstadoParada estado; + final String horaEstimada; + String? horaVisita; + String? notasVisita; + + ParadaRuta({ + required this.id, + required this.cliente, + required this.orden, + required this.estado, + required this.horaEstimada, + this.horaVisita, + this.notasVisita, + }); + + Map toMap(String rutaId) => { + 'id': id, + 'ruta_id': rutaId, + 'cliente_id': cliente.id, + 'orden': orden, + 'estado': estado.value, + 'hora_estimada': horaEstimada, + 'hora_visita': horaVisita, + 'notas_visita': notasVisita, + }; +} diff --git a/lib/models/pedido.dart b/lib/models/pedido.dart new file mode 100644 index 0000000..c203800 --- /dev/null +++ b/lib/models/pedido.dart @@ -0,0 +1,57 @@ +import 'cliente.dart'; +import 'item_pedido.dart'; + +enum EstadoPedido { pendiente, confirmado, entregado, cancelado } + +extension EstadoPedidoExt on EstadoPedido { + String get label { + switch (this) { + case EstadoPedido.pendiente: return 'Pendiente'; + case EstadoPedido.confirmado: return 'Confirmado'; + case EstadoPedido.entregado: return 'Entregado'; + case EstadoPedido.cancelado: return 'Cancelado'; + } + } + + static EstadoPedido fromString(String s) { + switch (s) { + case 'confirmado': return EstadoPedido.confirmado; + case 'entregado': return EstadoPedido.entregado; + case 'cancelado': return EstadoPedido.cancelado; + default: return EstadoPedido.pendiente; + } + } +} + +class Pedido { + final String id; + final Cliente cliente; + final List items; + EstadoPedido estado; + final DateTime fecha; + String notas; + String? firmaBase64; + + Pedido({ + required this.id, + required this.cliente, + required this.items, + required this.estado, + required this.fecha, + this.notas = '', + this.firmaBase64, + }); + + double get subtotal => items.fold(0, (s, i) => s + i.subtotal); + double get total => subtotal; + int get totalItems => items.fold(0, (s, i) => s + i.cantidad); + + Map toMap() => { + 'id': id, + 'cliente_id': cliente.id, + 'estado': estado.label.toLowerCase(), + 'fecha': fecha.toIso8601String(), + 'notas': notas, + 'firma_base64': firmaBase64, + }; +} diff --git a/lib/models/producto.dart b/lib/models/producto.dart new file mode 100644 index 0000000..06e6a24 --- /dev/null +++ b/lib/models/producto.dart @@ -0,0 +1,59 @@ +class Producto { + final String id; + final String nombre; + final String descripcion; + final String categoria; + final double precio; + final double precioMayorista; + final String unidad; + final int stock; + final String sku; + final String emoji; + + const Producto({ + required this.id, + required this.nombre, + required this.descripcion, + required this.categoria, + required this.precio, + required this.precioMayorista, + required this.unidad, + required this.stock, + required this.sku, + required this.emoji, + }); + + Map toMap() => { + 'id': id, + 'sku': sku, + 'nombre': nombre, + 'descripcion': descripcion, + 'categoria': categoria, + 'precio': precio, + 'precio_mayorista': precioMayorista, + 'unidad': unidad, + 'stock': stock, + 'emoji': emoji, + }; + + factory Producto.fromMap(Map m) => Producto( + id: m['id'] as String, + sku: m['sku'] as String? ?? '', + nombre: m['nombre'] as String, + descripcion: m['descripcion'] as String? ?? '', + categoria: m['categoria'] as String? ?? '', + precio: (m['precio'] as num).toDouble(), + precioMayorista: (m['precio_mayorista'] as num).toDouble(), + unidad: m['unidad'] as String? ?? 'unidad', + stock: m['stock'] as int? ?? 0, + emoji: m['emoji'] as String? ?? '📦', + ); + + Producto copyWith({int? stock, double? precio, double? precioMayorista}) => Producto( + id: id, sku: sku, nombre: nombre, descripcion: descripcion, + categoria: categoria, unidad: unidad, emoji: emoji, + precio: precio ?? this.precio, + precioMayorista: precioMayorista ?? this.precioMayorista, + stock: stock ?? this.stock, + ); +} diff --git a/lib/models/ruta.dart b/lib/models/ruta.dart new file mode 100644 index 0000000..11f0090 --- /dev/null +++ b/lib/models/ruta.dart @@ -0,0 +1,27 @@ +import 'parada_ruta.dart'; + +class Ruta { + final String id; + final String nombre; + final String zona; + final List paradas; + final DateTime fecha; + + Ruta({ + required this.id, + required this.nombre, + required this.zona, + required this.paradas, + required this.fecha, + }); + + int get visitadas => paradas.where((p) => p.estado == EstadoParada.visitado).length; + int get pendientes => paradas.where((p) => p.estado == EstadoParada.pendiente).length; + + Map toMap() => { + 'id': id, + 'nombre': nombre, + 'zona': zona, + 'fecha': fecha.toIso8601String(), + }; +} diff --git a/lib/models/vendedor.dart b/lib/models/vendedor.dart new file mode 100644 index 0000000..6529e61 --- /dev/null +++ b/lib/models/vendedor.dart @@ -0,0 +1,35 @@ +class Vendedor { + final String id; + final String nombre; + final String email; + final String telefono; + final String zona; + final String avatarInitials; + + const Vendedor({ + required this.id, + required this.nombre, + required this.email, + required this.telefono, + required this.zona, + required this.avatarInitials, + }); + + Map toMap() => { + 'id': id, + 'nombre': nombre, + 'email': email, + 'telefono': telefono, + 'zona': zona, + 'avatar_initials': avatarInitials, + }; + + factory Vendedor.fromMap(Map m) => Vendedor( + id: m['id'] as String, + nombre: m['nombre'] as String, + email: m['email'] as String, + telefono: m['telefono'] as String? ?? '', + zona: m['zona'] as String? ?? '', + avatarInitials: m['avatar_initials'] as String? ?? '', + ); +} diff --git a/lib/providers/app_provider.dart b/lib/providers/app_provider.dart new file mode 100644 index 0000000..4dc12cf --- /dev/null +++ b/lib/providers/app_provider.dart @@ -0,0 +1,311 @@ +import 'package:flutter/foundation.dart'; +import '../database/database_helper.dart'; +import '../database/db_seeder.dart'; +import '../models/vendedor.dart'; +import '../models/cliente.dart'; +import '../models/producto.dart'; +import '../models/pedido.dart'; +import '../models/item_pedido.dart'; +import '../models/ruta.dart'; +import '../models/parada_ruta.dart'; +import '../services/notification_service.dart'; + +class AppProvider extends ChangeNotifier { + final _db = DatabaseHelper(); + final NotificationService? _notifService; + + AppProvider({NotificationService? notifService}) : _notifService = notifService; + + // ── Estado de sesión ───────────────────────────────────────── + bool _isLoggedIn = false; + bool _loading = false; + String? _loginError; + Vendedor? _vendedor; + Ruta? _ruta; + List _pedidos = []; + List _productos = []; + List _clientes = []; + + // índices en memoria para joins rápidos + Map _clientesMap = {}; + Map _productosMap = {}; + + // ── Carrito activo ─────────────────────────────────────────── + Cliente? _clienteSeleccionado; + final List _carrito = []; + String _notasPedido = ''; + + // ── Getters ────────────────────────────────────────────────── + bool get isLoggedIn => _isLoggedIn; + bool get loading => _loading; + String? get loginError => _loginError; + + Vendedor get vendedor => _vendedor!; + Ruta get ruta => _ruta!; + List get pedidos => _pedidos; + List get productos => _productos; + List get clientes => _clientes; + + Cliente? get clienteSeleccionado => _clienteSeleccionado; + List get carrito => _carrito; + String get notasPedido => _notasPedido; + + double get totalCarrito => _carrito.fold(0, (s, i) => s + i.subtotal); + int get cantidadCarrito => _carrito.fold(0, (s, i) => s + i.cantidad); + + List get clientesSinParada { + final ids = _ruta?.paradas.map((p) => p.cliente.id).toSet() ?? {}; + return _clientes.where((c) => !ids.contains(c.id)).toList(); + } + + // ── Stats del día ──────────────────────────────────────────── + int get pedidosHoy => _pedidos.where((p) { + final now = DateTime.now(); + return p.fecha.day == now.day && p.fecha.month == now.month && + p.estado != EstadoPedido.cancelado; + }).length; + + double get ventasTotalesHoy => _pedidos.where((p) { + final now = DateTime.now(); + return p.fecha.day == now.day && p.fecha.month == now.month && + p.estado != EstadoPedido.cancelado; + }).fold(0, (s, p) => s + p.total); + + // ── Login / Logout ─────────────────────────────────────────── + + Future login(String email, String password) async { + _loginError = null; + _loading = true; + notifyListeners(); + + // Seed si es la primera vez + final seeded = await _db.isSeeded(); + if (!seeded) await DbSeeder(_db).seed(); + + final row = await _db.loginUsuario(email.trim(), password); + if (row == null) { + _loginError = 'Correo o contraseña incorrectos'; + _loading = false; + notifyListeners(); + return false; + } + + _vendedor = Vendedor.fromMap(row); + await _loadAllData(); + + _loading = false; + _isLoggedIn = true; + notifyListeners(); + return true; + } + + Future _loadAllData() async { + // 1. catálogo y clientes (base para joins) + _productos = await _db.getProductos(); + _clientes = await _db.getClientes(); + _productosMap = {for (final p in _productos) p.id: p}; + _clientesMap = {for (final c in _clientes) c.id: c}; + + // 2. Ruta de hoy (o crear una vacía) + final rutaId = await _db.getRutaIdHoy(); + if (rutaId != null) { + _ruta = await _db.getRutaConParadas(rutaId, _clientesMap) ?? _emptyRuta(); + } else { + _ruta = _emptyRuta(); + await _db.insertRuta(_ruta!); + } + + // 3. Pedidos + _pedidos = await _db.getPedidos(_clientesMap, _productosMap); + } + + Ruta _emptyRuta() => Ruta( + id: 'ruta_${DateTime.now().toIso8601String().substring(0, 10)}', + nombre: 'Ruta del día', + zona: _vendedor?.zona ?? '', + paradas: [], + fecha: DateTime.now(), + ); + + void logout() { + _isLoggedIn = false; + _vendedor = null; + _ruta = null; + _pedidos = []; + _productos = []; + _clientes = []; + _clientesMap = {}; + _productosMap = {}; + limpiarCarrito(); + notifyListeners(); + } + + // ── Clientes ───────────────────────────────────────────────── + + Future agregarCliente(Cliente cliente, {bool agregarARuta = false}) async { + await _db.insertCliente(cliente); + _clientes.add(cliente); + _clientesMap[cliente.id] = cliente; + if (agregarARuta) { + await agregarParadaARuta(cliente, _horaDefault()); + } else { + notifyListeners(); + } + } + + Future actualizarCliente(Cliente cliente) async { + await _db.updateCliente(cliente); + final idx = _clientes.indexWhere((c) => c.id == cliente.id); + if (idx >= 0) _clientes[idx] = cliente; + _clientesMap[cliente.id] = cliente; + notifyListeners(); + } + + // ── Productos ──────────────────────────────────────────────── + + Future actualizarStock(String productoId, int nuevoStock) async { + await _db.updateStock(productoId, nuevoStock); + final idx = _productos.indexWhere((p) => p.id == productoId); + if (idx >= 0) { + _productos[idx] = _productos[idx].copyWith(stock: nuevoStock); + _productosMap[productoId] = _productos[idx]; + if (nuevoStock <= 5) { + _notifService?.notifStockBajo(_productos[idx].nombre, nuevoStock); + } + } + notifyListeners(); + } + + // ── Ruta / Paradas ─────────────────────────────────────────── + + Future agregarParadaARuta(Cliente cliente, String horaEstimada) async { + final nuevaOrden = (_ruta?.paradas.length ?? 0) + 1; + final parada = ParadaRuta( + id: 'pr_${DateTime.now().millisecondsSinceEpoch}', + cliente: cliente, + orden: nuevaOrden, + estado: EstadoParada.pendiente, + horaEstimada: horaEstimada, + ); + await _db.insertParada(parada, _ruta!.id); + _ruta!.paradas.add(parada); + notifyListeners(); + } + + Future eliminarParada(String paradaId) async { + await _db.deleteParada(paradaId); + _ruta!.paradas.removeWhere((p) => p.id == paradaId); + // reordenar + for (int i = 0; i < _ruta!.paradas.length; i++) { + _ruta!.paradas[i] = ParadaRuta( + id: _ruta!.paradas[i].id, + cliente: _ruta!.paradas[i].cliente, + orden: i + 1, + estado: _ruta!.paradas[i].estado, + horaEstimada: _ruta!.paradas[i].horaEstimada, + horaVisita: _ruta!.paradas[i].horaVisita, + ); + } + await _db.reordenarParadas(_ruta!.paradas, _ruta!.id); + notifyListeners(); + } + + Future marcarParadaVisitada(String paradaId) async { + final hora = _horaActual(); + await _db.updateParadaEstado(paradaId, 'visitado', hora); + final parada = _ruta!.paradas.firstWhere((p) => p.id == paradaId); + parada.estado = EstadoParada.visitado; + parada.horaVisita = hora; + _notifService?.notifParadaVisitada(parada.cliente.nombre); + notifyListeners(); + } + + // ── Carrito ────────────────────────────────────────────────── + + void seleccionarCliente(Cliente cliente) { + _clienteSeleccionado = cliente; + notifyListeners(); + } + + void agregarAlCarrito(Producto producto, {bool esMayorista = false}) { + final precio = esMayorista ? producto.precioMayorista : producto.precio; + final existente = _carrito.where((i) => i.producto.id == producto.id); + if (existente.isNotEmpty) { + existente.first.cantidad++; + } else { + _carrito.add(ItemPedido(producto: producto, cantidad: 1, precioUnitario: precio)); + } + notifyListeners(); + } + + void quitarDelCarrito(String productoId) { + _carrito.removeWhere((i) => i.producto.id == productoId); + notifyListeners(); + } + + void actualizarCantidad(String productoId, int cantidad) { + if (cantidad <= 0) { quitarDelCarrito(productoId); return; } + _carrito.firstWhere((i) => i.producto.id == productoId).cantidad = cantidad; + notifyListeners(); + } + + void setNotasPedido(String notas) { + _notasPedido = notas; + notifyListeners(); + } + + void limpiarCarrito() { + _carrito.clear(); + _clienteSeleccionado = null; + _notasPedido = ''; + notifyListeners(); + } + + // ── Pedidos ────────────────────────────────────────────────── + + Future confirmarPedido({String? firmaBase64}) async { + final id = 'TTC-${(_pedidos.length + 1).toString().padLeft(4, '0')}'; + final pedido = Pedido( + id: id, + cliente: _clienteSeleccionado!, + items: List.from(_carrito), + estado: EstadoPedido.confirmado, + fecha: DateTime.now(), + notas: _notasPedido, + firmaBase64: firmaBase64, + ); + await _db.insertPedido(pedido); + _pedidos.insert(0, pedido); + _notifService?.notifPedidoConfirmado(id, _clienteSeleccionado!.nombre); + limpiarCarrito(); + notifyListeners(); + return pedido; + } + + Future cambiarEstadoPedido(String pedidoId, EstadoPedido nuevoEstado) async { + await _db.updateEstadoPedido(pedidoId, nuevoEstado.label.toLowerCase()); + final pedido = _pedidos.firstWhere((p) => p.id == pedidoId); + pedido.estado = nuevoEstado; + notifyListeners(); + } + + Future eliminarPedido(String pedidoId) async { + await _db.deletePedido(pedidoId); + _pedidos.removeWhere((p) => p.id == pedidoId); + notifyListeners(); + } + + // ── Helpers ────────────────────────────────────────────────── + + String _horaDefault() { + final now = DateTime.now(); + final h = now.hour.toString().padLeft(2, '0'); + final m = ((now.minute ~/ 15 + 1) * 15 % 60).toString().padLeft(2, '0'); + return '$h:$m'; + } + + String _horaActual() { + final now = DateTime.now(); + return '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}'; + } +} diff --git a/lib/screens/catalogo/catalogo_screen.dart b/lib/screens/catalogo/catalogo_screen.dart new file mode 100644 index 0000000..a04f9cd --- /dev/null +++ b/lib/screens/catalogo/catalogo_screen.dart @@ -0,0 +1,317 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../../providers/app_provider.dart'; +import '../../theme/app_theme.dart'; +import '../../models/producto.dart'; +import '../scanner/scanner_helper.dart'; + +class CatalogoScreen extends StatefulWidget { + const CatalogoScreen({Key? key}) : super(key: key); + + @override + State createState() => _CatalogoScreenState(); +} + +class _CatalogoScreenState extends State { + final _searchCtrl = TextEditingController(); + String _categoriaSeleccionada = 'Todos'; + String _query = ''; + + final _categorias = ['Todos', 'Redes & Conectividad', 'Telefonía & Móviles', 'Cómputo & Periféricos', 'Seguridad & Vigilancia', 'Servicios']; + + @override + void dispose() { + _searchCtrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final provider = context.watch(); + final fmt = NumberFormat.currency(locale: 'es_BO', symbol: 'Bs.', decimalDigits: 2); + + final filtrados = provider.productos.where((p) { + final matchCat = _categoriaSeleccionada == 'Todos' || p.categoria == _categoriaSeleccionada; + final matchQuery = _query.isEmpty || + p.nombre.toLowerCase().contains(_query.toLowerCase()) || + p.sku.toLowerCase().contains(_query.toLowerCase()); + return matchCat && matchQuery; + }).toList(); + + return Scaffold( + backgroundColor: AppTheme.bgColor, + appBar: AppBar( + title: const Text('Catálogo de Productos', style: TextStyle(fontWeight: FontWeight.bold)), + actions: [ + Padding( + padding: const EdgeInsets.only(right: 12), + child: Stack( + children: [ + IconButton( + icon: const Icon(Icons.shopping_cart_outlined), + onPressed: () {}, + ), + if (provider.cantidadCarrito > 0) + Positioned( + right: 6, + top: 6, + child: Container( + padding: const EdgeInsets.all(4), + decoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle), + child: Text( + '${provider.cantidadCarrito}', + style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.bold), + ), + ), + ), + ], + ), + ), + ], + ), + body: Column( + children: [ + Container( + color: AppTheme.primaryColor, + padding: const EdgeInsets.fromLTRB(16, 0, 16, 12), + child: TextField( + controller: _searchCtrl, + onChanged: (v) => setState(() => _query = v), + style: const TextStyle(color: Colors.white), + decoration: InputDecoration( + hintText: 'Buscar producto o SKU...', + hintStyle: const TextStyle(color: Colors.white60), + prefixIcon: const Icon(Icons.search, color: Colors.white70), + suffixIcon: _query.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear, color: Colors.white70), + onPressed: () { + _searchCtrl.clear(); + setState(() => _query = ''); + }, + ) + : IconButton( + tooltip: 'Escanear código', + icon: const Icon(Icons.qr_code_scanner, color: Colors.white70), + onPressed: () async { + final resultado = await abrirScanner(context, titulo: 'Buscar producto'); + if (resultado != null && mounted) { + _searchCtrl.text = resultado; + setState(() => _query = resultado); + } + }, + ), + filled: true, + fillColor: Colors.white.withOpacity(0.15), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide.none, + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: Colors.white54), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + ), + ), + // Categories + Container( + height: 44, + color: Colors.white, + child: ListView.builder( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + itemCount: _categorias.length, + itemBuilder: (context, i) { + final cat = _categorias[i]; + final selected = cat == _categoriaSeleccionada; + return Padding( + padding: const EdgeInsets.only(right: 8), + child: FilterChip( + label: Text(cat), + selected: selected, + onSelected: (_) => setState(() => _categoriaSeleccionada = cat), + selectedColor: AppTheme.primaryColor, + checkmarkColor: Colors.white, + labelStyle: TextStyle( + color: selected ? Colors.white : AppTheme.textPrimary, + fontSize: 12, + fontWeight: selected ? FontWeight.w600 : FontWeight.normal, + ), + ), + ); + }, + ), + ), + // Count + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row( + children: [ + Text( + '${filtrados.length} productos', + style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary), + ), + ], + ), + ), + // Grid + Expanded( + child: GridView.builder( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 80), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + childAspectRatio: 0.72, + crossAxisSpacing: 12, + mainAxisSpacing: 12, + ), + itemCount: filtrados.length, + itemBuilder: (context, i) => _buildProductCard(context, filtrados[i], provider, fmt), + ), + ), + ], + ), + ); + } + + Widget _buildProductCard(BuildContext context, Producto producto, AppProvider provider, NumberFormat fmt) { + final enCarrito = provider.carrito.where((i) => i.producto.id == producto.id); + final cantidadEnCarrito = enCarrito.isNotEmpty ? enCarrito.first.cantidad : 0; + + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.06), blurRadius: 8, offset: const Offset(0, 3))], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Product image placeholder + Container( + height: 110, + decoration: BoxDecoration( + color: AppTheme.primaryColor.withOpacity(0.06), + borderRadius: const BorderRadius.vertical(top: Radius.circular(14)), + ), + child: Stack( + children: [ + Center( + child: Text(producto.emoji, style: const TextStyle(fontSize: 52)), + ), + if (producto.stock < 20) + Positioned( + top: 8, + left: 8, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: AppTheme.dangerColor, + borderRadius: BorderRadius.circular(4), + ), + child: const Text('Bajo stock', style: TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.bold)), + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + producto.nombre, + style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 12, color: AppTheme.textPrimary), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 2), + Text( + 'SKU: ${producto.sku}', + style: const TextStyle(fontSize: 10, color: AppTheme.textSecondary), + ), + const SizedBox(height: 6), + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + fmt.format(producto.precio), + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: AppTheme.primaryColor), + ), + Text( + 'Mayor: ${fmt.format(producto.precioMayorista)}', + style: const TextStyle(fontSize: 9, color: AppTheme.textSecondary), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 8), + cantidadEnCarrito == 0 + ? SizedBox( + width: double.infinity, + height: 32, + child: ElevatedButton( + onPressed: () => provider.agregarAlCarrito(producto), + style: ElevatedButton.styleFrom( + padding: EdgeInsets.zero, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: const [ + Icon(Icons.add, size: 16), + SizedBox(width: 4), + Text('Agregar', style: TextStyle(fontSize: 12)), + ], + ), + ), + ) + : Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + _counterBtn(Icons.remove, () => provider.actualizarCantidad(producto.id, cantidadEnCarrito - 1)), + Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4), + decoration: BoxDecoration( + color: AppTheme.primaryColor.withOpacity(0.1), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + '$cantidadEnCarrito', + style: const TextStyle(fontWeight: FontWeight.bold, color: AppTheme.primaryColor), + ), + ), + _counterBtn(Icons.add, () => provider.agregarAlCarrito(producto)), + ], + ), + ], + ), + ), + ], + ), + ); + } + + Widget _counterBtn(IconData icon, VoidCallback onTap) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(6), + child: Container( + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: AppTheme.primaryColor, + borderRadius: BorderRadius.circular(6), + ), + child: Icon(icon, size: 16, color: Colors.white), + ), + ); + } +} diff --git a/lib/screens/clientes/cliente_form_screen.dart b/lib/screens/clientes/cliente_form_screen.dart new file mode 100644 index 0000000..39f3c85 --- /dev/null +++ b/lib/screens/clientes/cliente_form_screen.dart @@ -0,0 +1,369 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../../providers/app_provider.dart'; +import '../../theme/app_theme.dart'; +import '../../models/cliente.dart'; + +class ClienteFormScreen extends StatefulWidget { + final Cliente? clienteEditar; + + const ClienteFormScreen({Key? key, this.clienteEditar}) : super(key: key); + + @override + State createState() => _ClienteFormScreenState(); +} + +class _ClienteFormScreenState extends State { + final _formKey = GlobalKey(); + + final _nombreCtrl = TextEditingController(); + final _razonSocialCtrl = TextEditingController(); + final _nitCtrl = TextEditingController(); + final _telefonoCtrl = TextEditingController(); + final _direccionCtrl = TextEditingController(); + final _referenciaCtrl = TextEditingController(); + + String _categoria = 'Minorista'; + bool _agregarARuta = true; + bool _guardando = false; + + final _categorias = ['Minorista', 'Mayorista', 'Distribuidor', 'Empresa', 'Institución', 'Gobierno']; + + bool get esEdicion => widget.clienteEditar != null; + + @override + void initState() { + super.initState(); + if (esEdicion) { + final c = widget.clienteEditar!; + _nombreCtrl.text = c.nombre; + _razonSocialCtrl.text = c.razonSocial; + _nitCtrl.text = c.nit; + _telefonoCtrl.text = c.telefono; + _direccionCtrl.text = c.direccion; + _categoria = c.categoria; + } + } + + @override + void dispose() { + _nombreCtrl.dispose(); + _razonSocialCtrl.dispose(); + _nitCtrl.dispose(); + _telefonoCtrl.dispose(); + _direccionCtrl.dispose(); + _referenciaCtrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppTheme.bgColor, + appBar: AppBar( + title: Text( + esEdicion ? 'Editar cliente' : 'Nuevo punto de distribución', + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + body: Form( + key: _formKey, + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + _buildSectionHeader(Icons.store, 'Datos del negocio'), + const SizedBox(height: 12), + _buildCard(children: [ + _buildField( + controller: _nombreCtrl, + label: 'Nombre comercial *', + hint: 'Ej. Tienda Don Pepe', + icon: Icons.storefront_outlined, + validator: _required, + ), + const SizedBox(height: 14), + _buildField( + controller: _razonSocialCtrl, + label: 'Razón social', + hint: 'Ej. José García S.R.L.', + icon: Icons.business_outlined, + ), + const SizedBox(height: 14), + _buildField( + controller: _nitCtrl, + label: 'NIT / CI', + hint: 'Número de identificación tributaria', + icon: Icons.badge_outlined, + keyboardType: TextInputType.number, + ), + ]), + + const SizedBox(height: 20), + _buildSectionHeader(Icons.category_outlined, 'Categoría del cliente'), + const SizedBox(height: 12), + _buildCard(children: [ + Wrap( + spacing: 8, + runSpacing: 8, + children: _categorias.map((cat) { + final selected = _categoria == cat; + return GestureDetector( + onTap: () => setState(() => _categoria = cat), + child: AnimatedContainer( + duration: const Duration(milliseconds: 180), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + decoration: BoxDecoration( + color: selected ? AppTheme.primaryColor : const Color(0xFFF1F5F9), + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: selected ? AppTheme.primaryColor : const Color(0xFFCBD5E1), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + _iconForCategoria(cat), + size: 16, + color: selected ? Colors.white : AppTheme.textSecondary, + ), + const SizedBox(width: 6), + Text( + cat, + style: TextStyle( + fontSize: 13, + fontWeight: selected ? FontWeight.w600 : FontWeight.normal, + color: selected ? Colors.white : AppTheme.textPrimary, + ), + ), + ], + ), + ), + ); + }).toList(), + ), + ]), + + const SizedBox(height: 20), + _buildSectionHeader(Icons.contact_phone_outlined, 'Contacto'), + const SizedBox(height: 12), + _buildCard(children: [ + _buildField( + controller: _telefonoCtrl, + label: 'Teléfono / Celular *', + hint: 'Ej. +591 70000000', + icon: Icons.phone_outlined, + keyboardType: TextInputType.phone, + validator: _required, + ), + ]), + + const SizedBox(height: 20), + _buildSectionHeader(Icons.location_on_outlined, 'Ubicación'), + const SizedBox(height: 12), + _buildCard(children: [ + _buildField( + controller: _direccionCtrl, + label: 'Dirección *', + hint: 'Calle, número, zona o barrio', + icon: Icons.home_outlined, + validator: _required, + ), + const SizedBox(height: 14), + _buildField( + controller: _referenciaCtrl, + label: 'Referencia', + hint: 'Ej. Frente al parque, edificio azul...', + icon: Icons.signpost_outlined, + maxLines: 2, + ), + const SizedBox(height: 14), + // Simulated GPS pin button + OutlinedButton.icon( + icon: const Icon(Icons.my_location, size: 18), + label: const Text('Usar mi ubicación actual'), + onPressed: () { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('GPS: función disponible con permisos de ubicación'), + behavior: SnackBarBehavior.floating, + ), + ); + }, + style: OutlinedButton.styleFrom( + minimumSize: const Size(double.infinity, 44), + ), + ), + ]), + + if (!esEdicion) ...[ + const SizedBox(height: 20), + _buildSectionHeader(Icons.route_outlined, 'Ruta del día'), + const SizedBox(height: 12), + _buildCard(children: [ + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text( + 'Agregar a la ruta de hoy', + style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500), + ), + subtitle: const Text( + 'El punto se añade como parada pendiente', + style: TextStyle(fontSize: 12, color: AppTheme.textSecondary), + ), + value: _agregarARuta, + onChanged: (v) => setState(() => _agregarARuta = v), + activeColor: AppTheme.primaryColor, + ), + ]), + ], + + const SizedBox(height: 28), + _buildSubmitButton(context), + const SizedBox(height: 40), + ], + ), + ), + ); + } + + Widget _buildSectionHeader(IconData icon, String titulo) { + return Row( + children: [ + Icon(icon, size: 16, color: AppTheme.primaryColor), + const SizedBox(width: 8), + Text( + titulo, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: AppTheme.primaryColor, + letterSpacing: 0.3, + ), + ), + ], + ); + } + + Widget _buildCard({required List children}) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + boxShadow: [ + BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 8, offset: const Offset(0, 2)), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: children, + ), + ); + } + + Widget _buildField({ + required TextEditingController controller, + required String label, + required String hint, + required IconData icon, + TextInputType keyboardType = TextInputType.text, + int maxLines = 1, + String? Function(String?)? validator, + }) { + return TextFormField( + controller: controller, + keyboardType: keyboardType, + maxLines: maxLines, + validator: validator, + decoration: InputDecoration( + labelText: label, + hintText: hint, + prefixIcon: Icon(icon, size: 20), + ), + ); + } + + Widget _buildSubmitButton(BuildContext context) { + return SizedBox( + width: double.infinity, + height: 52, + child: ElevatedButton.icon( + icon: _guardando + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2.5), + ) + : Icon(esEdicion ? Icons.save_outlined : Icons.add_location_alt_outlined, size: 22), + label: Text( + _guardando + ? 'Guardando...' + : esEdicion + ? 'Guardar cambios' + : 'Registrar punto de distribución', + style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600), + ), + onPressed: _guardando ? null : () => _submit(context), + ), + ); + } + + Future _submit(BuildContext context) async { + if (!_formKey.currentState!.validate()) return; + + setState(() => _guardando = true); + await Future.delayed(const Duration(milliseconds: 600)); + + final provider = context.read(); + + final cliente = Cliente( + id: 'c_${DateTime.now().millisecondsSinceEpoch}', + nombre: _nombreCtrl.text.trim(), + razonSocial: _razonSocialCtrl.text.trim().isEmpty + ? _nombreCtrl.text.trim() + : _razonSocialCtrl.text.trim(), + nit: _nitCtrl.text.trim().isEmpty ? '—' : _nitCtrl.text.trim(), + telefono: _telefonoCtrl.text.trim(), + direccion: _direccionCtrl.text.trim(), + categoria: _categoria, + lat: -16.5, + lng: -68.1, + ); + + if (esEdicion) { + provider.actualizarCliente(cliente); + } else { + provider.agregarCliente(cliente, agregarARuta: _agregarARuta); + } + + if (mounted) { + Navigator.pop(context, cliente); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + esEdicion + ? '✓ ${cliente.nombre} actualizado' + : '✓ ${cliente.nombre} registrado${_agregarARuta ? ' y agregado a la ruta' : ''}', + ), + backgroundColor: AppTheme.successColor, + behavior: SnackBarBehavior.floating, + ), + ); + } + } + + String? _required(String? v) => + (v == null || v.trim().isEmpty) ? 'Este campo es obligatorio' : null; + + IconData _iconForCategoria(String cat) { + switch (cat) { + case 'Mayorista': return Icons.warehouse_outlined; + case 'Distribuidor': return Icons.local_shipping_outlined; + case 'Empresa': return Icons.business_outlined; + case 'Institución': return Icons.school_outlined; + case 'Gobierno': return Icons.account_balance_outlined; + default: return Icons.store_outlined; + } + } +} diff --git a/lib/screens/clientes/cliente_selector_screen.dart b/lib/screens/clientes/cliente_selector_screen.dart new file mode 100644 index 0000000..f3de247 --- /dev/null +++ b/lib/screens/clientes/cliente_selector_screen.dart @@ -0,0 +1,299 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import '../../models/cliente.dart'; +import '../../theme/app_theme.dart'; + +const int _kMaxResultados = 50; + +/// Pantalla de búsqueda de clientes. Retorna el [Cliente] seleccionado o null. +/// +/// Uso: +/// ```dart +/// final cliente = await Navigator.push( +/// context, +/// MaterialPageRoute(builder: (_) => ClienteSelectorScreen(clientes: provider.clientes)), +/// ); +/// ``` +class ClienteSelectorScreen extends StatefulWidget { + final List clientes; + final String titulo; + + const ClienteSelectorScreen({ + Key? key, + required this.clientes, + this.titulo = 'Seleccionar cliente', + }) : super(key: key); + + @override + State createState() => _ClienteSelectorScreenState(); +} + +class _ClienteSelectorScreenState extends State { + final _searchCtrl = TextEditingController(); + final _focusNode = FocusNode(); + Timer? _debounce; + + String _query = ''; + + @override + void initState() { + super.initState(); + // Autofocus al abrir + WidgetsBinding.instance!.addPostFrameCallback((_) => _focusNode.requestFocus()); + } + + @override + void dispose() { + _debounce?.cancel(); + _searchCtrl.dispose(); + _focusNode.dispose(); + super.dispose(); + } + + void _onSearchChanged(String value) { + _debounce?.cancel(); + _debounce = Timer(const Duration(milliseconds: 250), () { + setState(() => _query = value.trim()); + }); + } + + List get _filtrados { + if (_query.isEmpty) return const []; + final q = _query.toLowerCase(); + return widget.clientes.where((c) { + return c.nombre.toLowerCase().contains(q) || + c.nit.toLowerCase().contains(q) || + c.direccion.toLowerCase().contains(q) || + c.categoria.toLowerCase().contains(q); + }).take(_kMaxResultados + 1).toList(); // +1 para detectar si hay más + } + + @override + Widget build(BuildContext context) { + final resultados = _filtrados; + final hayMas = resultados.length > _kMaxResultados; + final visibles = hayMas ? resultados.take(_kMaxResultados).toList() : resultados; + + return Scaffold( + backgroundColor: AppTheme.bgColor, + appBar: AppBar( + titleSpacing: 0, + title: TextField( + controller: _searchCtrl, + focusNode: _focusNode, + onChanged: _onSearchChanged, + style: const TextStyle(color: Colors.white, fontSize: 15), + decoration: InputDecoration( + hintText: 'Buscar por nombre, NIT o dirección...', + hintStyle: TextStyle(color: Colors.white.withOpacity(0.55), fontSize: 14), + border: InputBorder.none, + prefixIcon: const Icon(Icons.search, color: Colors.white70, size: 22), + suffixIcon: _searchCtrl.text.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear, color: Colors.white70, size: 20), + onPressed: () { + _searchCtrl.clear(); + setState(() => _query = ''); + _focusNode.requestFocus(); + }, + ) + : null, + ), + ), + ), + body: _buildBody(visibles, hayMas), + ); + } + + Widget _buildBody(List visibles, bool hayMas) { + if (_query.isEmpty) { + return _buildEstadoInicial(); + } + if (visibles.isEmpty) { + return _buildSinResultados(); + } + return Column( + children: [ + _buildContador(visibles.length, hayMas), + Expanded( + child: ListView.builder( + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), + itemCount: visibles.length + (hayMas ? 1 : 0), + itemBuilder: (ctx, i) { + if (i == visibles.length) return _buildMasResultados(); + return _buildClienteTile(visibles[i]); + }, + ), + ), + ], + ); + } + + Widget _buildEstadoInicial() { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.search, size: 64, color: Colors.grey.shade300), + const SizedBox(height: 16), + Text( + '${widget.clientes.length} clientes disponibles', + style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500, color: AppTheme.textSecondary), + ), + const SizedBox(height: 6), + const Text( + 'Escribe para buscar', + style: TextStyle(fontSize: 13, color: AppTheme.textSecondary), + ), + ], + ), + ); + } + + Widget _buildSinResultados() { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.store_outlined, size: 56, color: Colors.grey.shade300), + const SizedBox(height: 14), + Text( + 'Sin resultados para "$_query"', + style: const TextStyle(fontSize: 14, color: AppTheme.textSecondary), + textAlign: TextAlign.center, + ), + const SizedBox(height: 6), + const Text( + 'Prueba con nombre, NIT o dirección', + style: TextStyle(fontSize: 12, color: AppTheme.textSecondary), + ), + ], + ), + ); + } + + Widget _buildContador(int cantidad, bool hayMas) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 10, 16, 4), + child: Row( + children: [ + Text( + hayMas + ? 'Mostrando $_kMaxResultados de más resultados — refina la búsqueda' + : '$cantidad resultado${cantidad == 1 ? '' : 's'}', + style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary), + ), + ], + ), + ); + } + + Widget _buildClienteTile(Cliente c) { + return Card( + margin: const EdgeInsets.only(bottom: 6), + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + side: const BorderSide(color: Color(0xFFE2E8F0)), + ), + child: InkWell( + borderRadius: BorderRadius.circular(10), + onTap: () => Navigator.pop(context, c), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + child: Row( + children: [ + CircleAvatar( + radius: 20, + backgroundColor: AppTheme.primaryColor.withOpacity(0.1), + child: const Icon(Icons.store, size: 20, color: AppTheme.primaryColor), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildTextoResaltado(c.nombre, _query, + const TextStyle(fontWeight: FontWeight.w600, fontSize: 14, color: AppTheme.textPrimary)), + const SizedBox(height: 2), + Text( + c.direccion, + style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 2), + Row( + children: [ + _buildChip(c.categoria), + if (c.nit.isNotEmpty) ...[ + const SizedBox(width: 6), + Text('NIT ${c.nit}', + style: const TextStyle(fontSize: 10, color: AppTheme.textSecondary)), + ], + ], + ), + ], + ), + ), + const Icon(Icons.chevron_right, color: AppTheme.textSecondary, size: 20), + ], + ), + ), + ), + ); + } + + Widget _buildMasResultados() { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Center( + child: Text( + 'Hay más resultados — refina la búsqueda para verlos', + style: TextStyle(fontSize: 12, color: Colors.grey.shade500), + textAlign: TextAlign.center, + ), + ), + ); + } + + Widget _buildChip(String texto) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: AppTheme.primaryColor.withOpacity(0.08), + borderRadius: BorderRadius.circular(4), + ), + child: Text(texto, style: const TextStyle(fontSize: 10, color: AppTheme.primaryColor, fontWeight: FontWeight.w500)), + ); + } + + /// Resalta el texto que coincide con la búsqueda en negrita + Widget _buildTextoResaltado(String texto, String query, TextStyle baseStyle) { + if (query.isEmpty) return Text(texto, style: baseStyle, maxLines: 1, overflow: TextOverflow.ellipsis); + final lower = texto.toLowerCase(); + final idx = lower.indexOf(query.toLowerCase()); + if (idx < 0) return Text(texto, style: baseStyle, maxLines: 1, overflow: TextOverflow.ellipsis); + + return RichText( + maxLines: 1, + overflow: TextOverflow.ellipsis, + text: TextSpan( + style: baseStyle, + children: [ + if (idx > 0) TextSpan(text: texto.substring(0, idx)), + TextSpan( + text: texto.substring(idx, idx + query.length), + style: baseStyle.copyWith( + backgroundColor: AppTheme.primaryColor.withOpacity(0.18), + color: AppTheme.primaryColor, + ), + ), + if (idx + query.length < texto.length) + TextSpan(text: texto.substring(idx + query.length)), + ], + ), + ); + } +} diff --git a/lib/screens/firma/firma_screen.dart b/lib/screens/firma/firma_screen.dart new file mode 100644 index 0000000..1613b36 --- /dev/null +++ b/lib/screens/firma/firma_screen.dart @@ -0,0 +1,322 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../../providers/app_provider.dart'; +import '../../theme/app_theme.dart'; +import '../../widgets/signature_pad.dart'; + +class FirmaScreen extends StatefulWidget { + const FirmaScreen({Key? key}) : super(key: key); + + @override + State createState() => _FirmaScreenState(); +} + +class _FirmaScreenState extends State { + final _padKey = GlobalKey(); + bool _firmado = false; + bool _guardando = false; + + final _fmt = NumberFormat.currency(locale: 'es_BO', symbol: 'Bs.', decimalDigits: 2); + + @override + Widget build(BuildContext context) { + final provider = context.watch(); + + return Scaffold( + backgroundColor: AppTheme.bgColor, + appBar: AppBar( + title: const Text('Firma del Cliente', style: TextStyle(fontWeight: FontWeight.bold)), + ), + body: Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Column( + children: [ + _buildResumenPedido(provider), + const SizedBox(height: 16), + _buildSignatureArea(context), + ], + ), + ), + ), + _buildBottomBar(context, provider), + ], + ), + ); + } + + Widget _buildResumenPedido(AppProvider provider) { + final cliente = provider.clienteSeleccionado; + return Container( + margin: const EdgeInsets.all(16), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + gradient: const LinearGradient( + colors: [Color(0xFF1E3A8A), Color(0xFF2563EB)], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(16), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: const [ + Icon(Icons.receipt_long, color: Colors.white70, size: 16), + SizedBox(width: 6), + Text('Resumen del pedido', style: TextStyle(color: Colors.white70, fontSize: 13)), + ], + ), + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Cliente:', style: TextStyle(color: Colors.white60, fontSize: 11)), + Text( + cliente?.nombre ?? '—', + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 15), + ), + const SizedBox(height: 4), + const Text('Dirección:', style: TextStyle(color: Colors.white60, fontSize: 11)), + Text( + cliente?.direccion ?? '—', + style: const TextStyle(color: Colors.white70, fontSize: 12), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + const SizedBox(width: 16), + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + const Text('Total:', style: TextStyle(color: Colors.white70, fontSize: 13)), + Text( + _fmt.format(provider.totalCarrito), + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 24), + ), + Text( + '${provider.cantidadCarrito} unidades', + style: const TextStyle(color: Colors.white60, fontSize: 11), + ), + ], + ), + ], + ), + const Divider(color: Colors.white24, height: 20), + Text( + '${provider.carrito.length} producto(s): ' + '${provider.carrito.map((i) => i.producto.nombre.split(' ').first).take(3).join(', ')}' + '${provider.carrito.length > 3 ? '...' : ''}', + style: const TextStyle(color: Colors.white60, fontSize: 11), + ), + ], + ), + ); + } + + Widget _buildSignatureArea(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: const [ + Text('Firma de conformidad', style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold, color: AppTheme.textPrimary)), + Text('El cliente firma confirmando el pedido', style: TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + ], + ), + TextButton.icon( + icon: const Icon(Icons.refresh, size: 16), + label: const Text('Limpiar'), + onPressed: () { + _padKey.currentState?.clear(); + setState(() => _firmado = false); + }, + ), + ], + ), + const SizedBox(height: 10), + Container( + height: 220, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(14), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.08), blurRadius: 10, offset: const Offset(0, 4))], + ), + child: Stack( + children: [ + SignaturePad( + key: _padKey, + onChanged: (strokes) { + setState(() => _firmado = strokes.isNotEmpty); + }, + ), + if (!_firmado) + Positioned.fill( + child: IgnorePointer( + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.draw_outlined, size: 40, color: Colors.grey.shade300), + const SizedBox(height: 8), + Text( + 'Firmar aquí', + style: TextStyle(fontSize: 16, color: Colors.grey.shade400, fontWeight: FontWeight.w500), + ), + ], + ), + ), + ), + ), + ], + ), + ), + const SizedBox(height: 10), + const Divider(), + Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: const [ + Text('Nombre del firmante:', style: TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + Text('Responsable de recepción', style: TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + ], + ), + ), + if (_firmado) + Container( + margin: const EdgeInsets.only(top: 8), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: AppTheme.successColor.withOpacity(0.1), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: AppTheme.successColor.withOpacity(0.3)), + ), + child: Row( + children: const [ + Icon(Icons.check_circle_outline, color: AppTheme.successColor, size: 16), + SizedBox(width: 8), + Text('Firma registrada', style: TextStyle(color: AppTheme.successColor, fontSize: 12, fontWeight: FontWeight.w600)), + ], + ), + ), + ], + ), + ); + } + + Widget _buildBottomBar(BuildContext context, AppProvider provider) { + return Container( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 28), + decoration: const BoxDecoration( + color: Colors.white, + boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 8, offset: Offset(0, -2))], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: () => Navigator.pop(context), + child: const Text('Volver al pedido'), + ), + ), + const SizedBox(width: 12), + Expanded( + flex: 2, + child: ElevatedButton.icon( + icon: _guardando + ? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2)) + : const Icon(Icons.check_circle_outline, size: 22), + label: Text(_guardando ? 'Guardando...' : 'Confirmar pedido', + style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)), + onPressed: (!_firmado || _guardando) + ? null + : () async { + setState(() => _guardando = true); + final pedido = await provider.confirmarPedido(firmaBase64: 'signed'); + if (mounted) { + _showSuccess(context, pedido.id); + } + }, + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 14), + ), + ), + ), + ], + ), + const SizedBox(height: 8), + if (!_firmado) + const Text( + 'El cliente debe firmar para confirmar el pedido', + style: TextStyle(fontSize: 11, color: AppTheme.textSecondary), + textAlign: TextAlign.center, + ), + ], + ), + ); + } + + void _showSuccess(BuildContext context, String pedidoId) { + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 72, + height: 72, + decoration: const BoxDecoration( + color: Color(0xFFDCFCE7), + shape: BoxShape.circle, + ), + child: const Icon(Icons.check, color: AppTheme.successColor, size: 40), + ), + const SizedBox(height: 16), + const Text('¡Pedido confirmado!', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: AppTheme.textPrimary)), + const SizedBox(height: 8), + Text( + '$pedidoId ha sido registrado correctamente.', + style: const TextStyle(color: AppTheme.textSecondary, fontSize: 13), + textAlign: TextAlign.center, + ), + ], + ), + actions: [ + SizedBox( + width: double.infinity, + child: ElevatedButton( + onPressed: () { + Navigator.of(context) + ..pop() + ..pop() + ..pop(); + }, + child: const Text('Volver al inicio'), + ), + ), + ], + ), + ); + } +} diff --git a/lib/screens/home/home_screen.dart b/lib/screens/home/home_screen.dart new file mode 100644 index 0000000..36c456e --- /dev/null +++ b/lib/screens/home/home_screen.dart @@ -0,0 +1,539 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../../providers/app_provider.dart'; +import '../../services/notification_service.dart'; +import '../../theme/app_theme.dart'; +import '../../widgets/stat_card.dart'; +import '../../models/pedido.dart'; +import '../notificaciones/notificaciones_screen.dart'; + +class HomeScreen extends StatelessWidget { + const HomeScreen({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + final provider = context.watch(); + final notifService = context.watch(); + final fmt = NumberFormat.currency(locale: 'es_BO', symbol: 'Bs.', decimalDigits: 2); + + return Scaffold( + backgroundColor: AppTheme.bgColor, + body: RefreshIndicator( + onRefresh: () async => await Future.delayed(const Duration(milliseconds: 600)), + child: CustomScrollView( + slivers: [ + _buildSliverAppBar(context, provider, notifService), + SliverPadding( + padding: const EdgeInsets.symmetric(horizontal: 16), + sliver: SliverList( + delegate: SliverChildListDelegate([ + const SizedBox(height: 16), + _buildStatsGrid(context, provider, fmt), + const SizedBox(height: 20), + _buildRutaCard(context, provider), + const SizedBox(height: 20), + _buildRecentOrders(context, provider, fmt), + const SizedBox(height: 20), + _buildQuickActions(context, notifService), + const SizedBox(height: 80), + ]), + ), + ), + ], + ), + ), + ); + } + + Widget _buildSliverAppBar( + BuildContext context, + AppProvider provider, + NotificationService notifService, + ) { + final hour = DateTime.now().hour; + final greeting = hour < 12 ? 'Buenos días' : hour < 18 ? 'Buenas tardes' : 'Buenas noches'; + final dateStr = DateFormat('EEEE, d \'de\' MMMM', 'es').format(DateTime.now()); + final unread = notifService.unreadCount; + + return SliverAppBar( + expandedHeight: 160, + floating: false, + pinned: true, + backgroundColor: AppTheme.primaryColor, + actions: [ + Stack( + alignment: Alignment.center, + children: [ + IconButton( + icon: const Icon(Icons.notifications_outlined, color: Colors.white, size: 26), + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const NotificacionesScreen()), + ), + ), + if (unread > 0) + Positioned( + top: 10, + right: 10, + child: Container( + width: 17, + height: 17, + decoration: BoxDecoration( + color: const Color(0xFFEF4444), + shape: BoxShape.circle, + border: Border.all(color: AppTheme.primaryColor, width: 1.5), + ), + child: Center( + child: Text( + unread > 9 ? '9+' : '$unread', + style: const TextStyle( + color: Colors.white, + fontSize: 9, + fontWeight: FontWeight.bold, + height: 1, + ), + ), + ), + ), + ), + ], + ), + ], + flexibleSpace: FlexibleSpaceBar( + background: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + colors: [Color(0xFF1E3A8A), Color(0xFF2563EB)], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + ), + child: SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(20, 16, 60, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + CircleAvatar( + radius: 22, + backgroundColor: Colors.white.withOpacity(0.2), + child: Text( + provider.vendedor.avatarInitials, + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '$greeting,', + style: const TextStyle(color: Colors.white70, fontSize: 13), + ), + Text( + provider.vendedor.nombre, + style: const TextStyle(color: Colors.white, fontSize: 17, fontWeight: FontWeight.bold), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 10), + Row( + children: [ + const Icon(Icons.calendar_today, color: Colors.white60, size: 14), + const SizedBox(width: 6), + Text( + dateStr, + style: const TextStyle(color: Colors.white70, fontSize: 13), + ), + const Spacer(), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.2), + borderRadius: BorderRadius.circular(12), + ), + child: Row( + children: [ + const Icon(Icons.location_on, color: Colors.white, size: 14), + const SizedBox(width: 4), + Text( + provider.vendedor.zona, + style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w500), + ), + ], + ), + ), + ], + ), + ], + ), + ), + ), + ), + title: Text( + greeting, + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + titlePadding: const EdgeInsets.only(left: 16, bottom: 12), + ), + ); + } + + Widget _buildStatsGrid(BuildContext context, AppProvider provider, NumberFormat fmt) { + final ruta = provider.ruta; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Resumen del día', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: AppTheme.textPrimary)), + const SizedBox(height: 12), + GridView.count( + crossAxisCount: 2, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + crossAxisSpacing: 12, + mainAxisSpacing: 12, + childAspectRatio: 1.5, + children: [ + StatCard( + titulo: 'Pedidos hoy', + valor: '${provider.pedidosHoy}', + subtitulo: 'confirmados', + icono: Icons.receipt_long, + color: AppTheme.primaryColor, + ), + StatCard( + titulo: 'Ventas del día', + valor: fmt.format(provider.ventasTotalesHoy), + subtitulo: 'total acumulado', + icono: Icons.attach_money, + color: AppTheme.successColor, + ), + StatCard( + titulo: 'Clientes visitados', + valor: '${ruta.visitadas}/${ruta.paradas.length}', + subtitulo: 'en la ruta', + icono: Icons.store, + color: AppTheme.accentColor, + ), + StatCard( + titulo: 'Paradas restantes', + valor: '${ruta.pendientes}', + subtitulo: 'por visitar', + icono: Icons.flag_outlined, + color: AppTheme.warningColor, + ), + ], + ), + ], + ); + } + + Widget _buildRutaCard(BuildContext context, AppProvider provider) { + final ruta = provider.ruta; + final proxima = ruta.paradas.where((p) => p.estado.name == 'pendiente').isNotEmpty + ? ruta.paradas.firstWhere((p) => p.estado.name == 'pendiente') + : null; + + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + gradient: const LinearGradient( + colors: [Color(0xFF0F172A), Color(0xFF1E3A8A)], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(16), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.route, color: Colors.white, size: 20), + const SizedBox(width: 8), + Expanded( + child: Text( + ruta.nombre, + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 15), + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.15), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + '${ruta.visitadas}/${ruta.paradas.length} paradas', + style: const TextStyle(color: Colors.white, fontSize: 12), + ), + ), + ], + ), + const SizedBox(height: 12), + ClipRRect( + borderRadius: BorderRadius.circular(4), + child: LinearProgressIndicator( + value: ruta.paradas.isEmpty ? 0 : ruta.visitadas / ruta.paradas.length, + backgroundColor: Colors.white.withOpacity(0.2), + valueColor: const AlwaysStoppedAnimation(Color(0xFF34D399)), + minHeight: 6, + ), + ), + if (proxima != null) ...[ + const SizedBox(height: 12), + Row( + children: [ + const Icon(Icons.navigation, color: Color(0xFF34D399), size: 16), + const SizedBox(width: 6), + const Text('Próxima parada:', style: TextStyle(color: Colors.white60, fontSize: 12)), + const SizedBox(width: 6), + Expanded( + child: Text( + proxima.cliente.nombre, + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w600, fontSize: 13), + overflow: TextOverflow.ellipsis, + ), + ), + Text( + proxima.horaEstimada, + style: const TextStyle(color: Color(0xFFFBBF24), fontSize: 13, fontWeight: FontWeight.bold), + ), + ], + ), + ], + ], + ), + ); + } + + Widget _buildRecentOrders(BuildContext context, AppProvider provider, NumberFormat fmt) { + final recientes = provider.pedidos.take(3).toList(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Pedidos recientes', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: AppTheme.textPrimary)), + TextButton( + onPressed: () {}, + child: const Text('Ver todos'), + ), + ], + ), + const SizedBox(height: 8), + ...recientes.map((pedido) => _buildOrderTile(context, pedido, fmt)).toList(), + ], + ); + } + + Widget _buildOrderTile(BuildContext context, Pedido pedido, NumberFormat fmt) { + final estadoColor = AppTheme.estadoColor(pedido.estado.label); + return Container( + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6, offset: const Offset(0, 2)), + ], + ), + child: Row( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: estadoColor.withOpacity(0.12), + borderRadius: BorderRadius.circular(10), + ), + child: Icon(Icons.receipt_outlined, color: estadoColor, size: 20), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(pedido.id, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: AppTheme.textPrimary)), + Text(pedido.cliente.nombre, + style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + ], + ), + ), + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text(fmt.format(pedido.total), + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: AppTheme.textPrimary)), + const SizedBox(height: 4), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: estadoColor.withOpacity(0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + pedido.estado.label, + style: TextStyle(fontSize: 10, color: estadoColor, fontWeight: FontWeight.w600), + ), + ), + ], + ), + ], + ), + ); + } + + Widget _buildQuickActions(BuildContext context, NotificationService notifService) { + final staticActions = [ + {'icon': Icons.add_shopping_cart, 'label': 'Nuevo\nPedido', 'color': AppTheme.primaryColor}, + {'icon': Icons.map_outlined, 'label': 'Ver\nRuta', 'color': AppTheme.successColor}, + {'icon': Icons.inventory_2_outlined, 'label': 'Catálogo', 'color': AppTheme.accentColor}, + ]; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Acciones rápidas', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: AppTheme.textPrimary)), + const SizedBox(height: 12), + Row( + children: [ + ...staticActions.map((a) { + final color = a['color'] as Color; + return Expanded( + child: GestureDetector( + onTap: () {}, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 4), + padding: const EdgeInsets.symmetric(vertical: 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow(color: color.withOpacity(0.1), blurRadius: 8, offset: const Offset(0, 3)), + ], + ), + child: Column( + children: [ + Icon(a['icon'] as IconData, color: color, size: 26), + const SizedBox(height: 6), + Text( + a['label'] as String, + style: TextStyle(fontSize: 11, color: color, fontWeight: FontWeight.w600), + textAlign: TextAlign.center, + ), + ], + ), + ), + ), + ); + }).toList(), + Expanded( + child: GestureDetector( + onTap: () => notifService.dispararDemo(), + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 4), + padding: const EdgeInsets.symmetric(vertical: 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: const Color(0xFF7C3AED).withOpacity(0.15), + blurRadius: 8, + offset: const Offset(0, 3), + ), + ], + ), + child: Column( + children: const [ + Icon(Icons.notifications_active, color: Color(0xFF7C3AED), size: 26), + SizedBox(height: 6), + Text( + 'Demo\nNotif.', + style: TextStyle(fontSize: 11, color: Color(0xFF7C3AED), fontWeight: FontWeight.w600), + textAlign: TextAlign.center, + ), + ], + ), + ), + ), + ), + ], + ), + const SizedBox(height: 12), + _buildNotifDemoCard(context, notifService), + ], + ); + } + + Widget _buildNotifDemoCard(BuildContext context, NotificationService notifService) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + gradient: const LinearGradient( + colors: [Color(0xFF4C1D95), Color(0xFF7C3AED)], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(14), + ), + child: Row( + children: [ + Container( + width: 44, + height: 44, + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.15), + shape: BoxShape.circle, + ), + child: const Icon(Icons.notifications_active, color: Colors.white, size: 22), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: const [ + Text( + 'Demo de notificaciones', + style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 14), + ), + SizedBox(height: 2), + Text( + 'Pulsa para disparar 5 notificaciones de muestra con banner animado', + style: TextStyle(color: Colors.white70, fontSize: 11), + ), + ], + ), + ), + const SizedBox(width: 10), + ElevatedButton( + onPressed: () => notifService.dispararDemo(), + style: ElevatedButton.styleFrom( + primary: Colors.white, + onPrimary: const Color(0xFF7C3AED), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + elevation: 0, + ), + child: const Text('Probar', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13)), + ), + ], + ), + ); + } +} diff --git a/lib/screens/login/login_screen.dart b/lib/screens/login/login_screen.dart new file mode 100644 index 0000000..38e66a5 --- /dev/null +++ b/lib/screens/login/login_screen.dart @@ -0,0 +1,249 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../../providers/app_provider.dart'; +import '../../theme/app_theme.dart'; + +class LoginScreen extends StatefulWidget { + const LoginScreen({Key? key}) : super(key: key); + + @override + State createState() => _LoginScreenState(); +} + +class _LoginScreenState extends State { + final _emailCtrl = TextEditingController(text: 'admin@telcotronics.com'); + final _passCtrl = TextEditingController(text: 'Microbot%'); + bool _obscure = true; + bool _loading = false; + String? _error; + + @override + void dispose() { + _emailCtrl.dispose(); + _passCtrl.dispose(); + super.dispose(); + } + + Future _login() async { + setState(() { _loading = true; _error = null; }); + final ok = await context.read().login( + _emailCtrl.text.trim(), _passCtrl.text); + if (!ok && mounted) { + setState(() { + _loading = false; + _error = context.read().loginError; + }); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + colors: [Color(0xFF1E3A8A), Color(0xFF1E40AF), Color(0xFF2563EB)], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + ), + child: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 28), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _buildLogo(), + const SizedBox(height: 40), + _buildCard(), + const SizedBox(height: 24), + _buildVersion(), + ], + ), + ), + ), + ), + ), + ); + } + + Widget _buildLogo() { + return Column( + children: [ + Container( + width: 96, + height: 96, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(24), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.25), + blurRadius: 20, + offset: const Offset(0, 8), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(24), + child: Image.asset( + 'assets/icon/icon.png', + width: 96, + height: 96, + fit: BoxFit.cover, + ), + ), + ), + const SizedBox(height: 20), + const Text( + 'Agente Ventas', + style: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold, + color: Colors.white, + letterSpacing: 1.0, + ), + ), + const SizedBox(height: 4), + Text( + 'by SIGMAC', + style: TextStyle( + fontSize: 13, + color: Colors.white.withOpacity(0.65), + letterSpacing: 2.0, + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 6), + Text( + 'Gestión de rutas y pedidos de campo', + style: TextStyle( + fontSize: 13, + color: Colors.white.withOpacity(0.8), + ), + ), + ], + ); + } + + Widget _buildCard() { + return Container( + padding: const EdgeInsets.all(28), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.2), + blurRadius: 20, + offset: const Offset(0, 8), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Iniciar sesión', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: AppTheme.textPrimary, + ), + ), + const SizedBox(height: 6), + const Text( + 'Ingresa tus credenciales para continuar', + style: TextStyle(fontSize: 13, color: AppTheme.textSecondary), + ), + const SizedBox(height: 24), + TextField( + controller: _emailCtrl, + keyboardType: TextInputType.emailAddress, + decoration: const InputDecoration( + labelText: 'Correo electrónico', + prefixIcon: Icon(Icons.email_outlined), + ), + ), + const SizedBox(height: 14), + TextField( + controller: _passCtrl, + obscureText: _obscure, + decoration: InputDecoration( + labelText: 'Contraseña', + prefixIcon: const Icon(Icons.lock_outline), + suffixIcon: IconButton( + icon: Icon(_obscure ? Icons.visibility_outlined : Icons.visibility_off_outlined), + onPressed: () => setState(() => _obscure = !_obscure), + ), + ), + ), + const SizedBox(height: 8), + Align( + alignment: Alignment.centerRight, + child: TextButton( + onPressed: () {}, + child: const Text('¿Olvidaste tu contraseña?'), + ), + ), + if (_error != null) ...[ + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: AppTheme.dangerColor.withOpacity(0.08), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: AppTheme.dangerColor.withOpacity(0.3)), + ), + child: Row( + children: [ + const Icon(Icons.error_outline, color: AppTheme.dangerColor, size: 16), + const SizedBox(width: 8), + Expanded( + child: Text( + _error!, + style: const TextStyle(fontSize: 12, color: AppTheme.dangerColor), + ), + ), + ], + ), + ), + const SizedBox(height: 8), + ], + const SizedBox(height: 8), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: _loading ? null : _login, + child: _loading + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator( + strokeWidth: 2.5, + color: Colors.white, + ), + ) + : Row( + mainAxisAlignment: MainAxisAlignment.center, + children: const [ + Icon(Icons.login, size: 20), + SizedBox(width: 8), + Text('Ingresar', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)), + ], + ), + ), + ), + ], + ), + ); + } + + Widget _buildVersion() { + return Text( + 'v1.0.0 • SIGMAC • Telcotronics', + style: TextStyle(fontSize: 12, color: Colors.white.withOpacity(0.6)), + ); + } +} diff --git a/lib/screens/main_shell.dart b/lib/screens/main_shell.dart new file mode 100644 index 0000000..83cd3a9 --- /dev/null +++ b/lib/screens/main_shell.dart @@ -0,0 +1,78 @@ +import 'package:flutter/material.dart'; +import '../theme/app_theme.dart'; +import 'home/home_screen.dart'; +import 'rutas/rutas_screen.dart'; +import 'pedidos/pedidos_screen.dart'; +import 'catalogo/catalogo_screen.dart'; +import 'perfil/perfil_screen.dart'; + +class MainShell extends StatefulWidget { + const MainShell({Key? key}) : super(key: key); + + @override + State createState() => _MainShellState(); +} + +class _MainShellState extends State { + int _currentIndex = 0; + + final _screens = const [ + HomeScreen(), + RutasScreen(), + PedidosScreen(), + CatalogoScreen(), + PerfilScreen(), + ]; + + @override + Widget build(BuildContext context) { + return Scaffold( + body: IndexedStack( + index: _currentIndex, + children: _screens, + ), + bottomNavigationBar: Container( + decoration: const BoxDecoration( + boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 10, offset: Offset(0, -2))], + ), + child: BottomNavigationBar( + currentIndex: _currentIndex, + onTap: (i) => setState(() => _currentIndex = i), + type: BottomNavigationBarType.fixed, + backgroundColor: Colors.white, + selectedItemColor: AppTheme.primaryColor, + unselectedItemColor: const Color(0xFF94A3B8), + selectedFontSize: 11, + unselectedFontSize: 11, + items: const [ + BottomNavigationBarItem( + icon: Icon(Icons.home_outlined), + activeIcon: Icon(Icons.home_rounded), + label: 'Inicio', + ), + BottomNavigationBarItem( + icon: Icon(Icons.route_outlined), + activeIcon: Icon(Icons.route_rounded), + label: 'Mi Ruta', + ), + BottomNavigationBarItem( + icon: Icon(Icons.receipt_long_outlined), + activeIcon: Icon(Icons.receipt_long_rounded), + label: 'Pedidos', + ), + BottomNavigationBarItem( + icon: Icon(Icons.inventory_2_outlined), + activeIcon: Icon(Icons.inventory_2_rounded), + label: 'Catálogo', + ), + BottomNavigationBarItem( + icon: Icon(Icons.person_outline_rounded), + activeIcon: Icon(Icons.person_rounded), + label: 'Perfil', + ), + ], + ), + ), + ); + } +} diff --git a/lib/screens/notificaciones/notificaciones_screen.dart b/lib/screens/notificaciones/notificaciones_screen.dart new file mode 100644 index 0000000..6ffab6f --- /dev/null +++ b/lib/screens/notificaciones/notificaciones_screen.dart @@ -0,0 +1,296 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../../services/notification_service.dart'; +import '../../models/notificacion.dart'; +import '../../theme/app_theme.dart'; + +class NotificacionesScreen extends StatelessWidget { + const NotificacionesScreen({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, service, _) { + final notifs = service.notifications; + return Scaffold( + backgroundColor: AppTheme.bgColor, + body: CustomScrollView( + slivers: [ + _buildAppBar(context, service), + if (notifs.isEmpty) + _buildEmptyState() + else + _buildList(context, service, notifs), + ], + ), + ); + }, + ); + } + + Widget _buildAppBar(BuildContext context, NotificationService service) { + return SliverAppBar( + pinned: true, + backgroundColor: AppTheme.primaryColor, + title: Row( + children: [ + const Text( + 'Notificaciones', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), + ), + if (service.unreadCount > 0) ...[ + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.2), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + '${service.unreadCount} sin leer', + style: const TextStyle(fontSize: 11, color: Colors.white), + ), + ), + ], + ], + ), + actions: [ + if (service.unreadCount > 0) + TextButton.icon( + icon: const Icon(Icons.done_all, color: Colors.white70, size: 18), + label: const Text( + 'Marcar todo', + style: TextStyle(color: Colors.white70, fontSize: 12), + ), + onPressed: service.marcarTodasLeidas, + ), + ], + ); + } + + Widget _buildEmptyState() { + return SliverFillRemaining( + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + width: 80, + height: 80, + decoration: const BoxDecoration( + color: Color(0xFFEFF6FF), + shape: BoxShape.circle, + ), + child: const Icon( + Icons.notifications_none_rounded, + size: 40, + color: Color(0xFF93C5FD), + ), + ), + const SizedBox(height: 16), + const Text( + 'Sin notificaciones', + style: TextStyle( + fontSize: 17, + fontWeight: FontWeight.bold, + color: AppTheme.textPrimary, + ), + ), + const SizedBox(height: 8), + const Text( + 'Aquí aparecerán alertas de pedidos,\nstock, rutas y más.', + style: TextStyle(fontSize: 13, color: AppTheme.textSecondary), + textAlign: TextAlign.center, + ), + ], + ), + ), + ); + } + + Widget _buildList( + BuildContext context, + NotificationService service, + List notifs, + ) { + final hoy = []; + final antes = []; + final now = DateTime.now(); + + for (final n in notifs) { + if (n.fecha.day == now.day && n.fecha.month == now.month && n.fecha.year == now.year) { + hoy.add(n); + } else { + antes.add(n); + } + } + + final sections = []; + + if (hoy.isNotEmpty) { + sections.add(_buildSectionHeader('Hoy')); + sections.addAll(hoy.map((n) => _buildNotifCard(context, service, n))); + } + if (antes.isNotEmpty) { + sections.add(_buildSectionHeader('Anteriores')); + sections.addAll(antes.map((n) => _buildNotifCard(context, service, n))); + } + + return SliverList( + delegate: SliverChildListDelegate([ + ...sections, + const SizedBox(height: 24), + ]), + ); + } + + Widget _buildSectionHeader(String label) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 6), + child: Text( + label, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + color: AppTheme.textSecondary, + letterSpacing: 0.5, + ), + ), + ); + } + + Widget _buildNotifCard( + BuildContext context, + NotificationService service, + Notificacion notif, + ) { + final color = notif.tipo.color; + final timeFmt = DateFormat('HH:mm', 'es'); + final dateFmt = DateFormat('d MMM', 'es'); + final isToday = notif.fecha.day == DateTime.now().day; + final timeLabel = isToday ? timeFmt.format(notif.fecha) : dateFmt.format(notif.fecha); + + return Dismissible( + key: Key(notif.id), + direction: DismissDirection.endToStart, + background: Container( + alignment: Alignment.centerRight, + padding: const EdgeInsets.only(right: 24), + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + decoration: BoxDecoration( + color: AppTheme.dangerColor, + borderRadius: BorderRadius.circular(14), + ), + child: const Icon(Icons.delete_outline, color: Colors.white, size: 24), + ), + onDismissed: (_) => service.eliminar(notif.id), + child: GestureDetector( + onTap: () { + if (!notif.leida) service.marcarLeida(notif.id); + }, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: notif.leida ? Colors.white : const Color(0xFFEFF6FF), + borderRadius: BorderRadius.circular(14), + border: notif.leida + ? Border.all(color: Colors.transparent) + : Border(left: BorderSide(color: color, width: 3)), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.04), + blurRadius: 6, + offset: const Offset(0, 2), + ), + ], + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: color.withOpacity(0.12), + shape: BoxShape.circle, + ), + child: Icon(notif.tipo.icono, color: color, size: 20), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Text( + notif.titulo, + style: TextStyle( + fontSize: 13, + fontWeight: notif.leida ? FontWeight.w500 : FontWeight.bold, + color: AppTheme.textPrimary, + ), + ), + ), + const SizedBox(width: 8), + Text( + timeLabel, + style: const TextStyle(fontSize: 11, color: AppTheme.textSecondary), + ), + ], + ), + const SizedBox(height: 4), + Text( + notif.cuerpo, + style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary), + ), + const SizedBox(height: 6), + Row( + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: color.withOpacity(0.1), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + notif.tipo.label, + style: TextStyle( + fontSize: 10, + color: color, + fontWeight: FontWeight.w600, + ), + ), + ), + if (!notif.leida) ...[ + const SizedBox(width: 8), + Container( + width: 7, + height: 7, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + ), + ), + const SizedBox(width: 4), + Text( + 'Sin leer', + style: TextStyle(fontSize: 10, color: color, fontWeight: FontWeight.w500), + ), + ], + ], + ), + ], + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/screens/pedidos/pedido_detail_screen.dart b/lib/screens/pedidos/pedido_detail_screen.dart new file mode 100644 index 0000000..9ae319e --- /dev/null +++ b/lib/screens/pedidos/pedido_detail_screen.dart @@ -0,0 +1,315 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../../providers/app_provider.dart'; +import '../../theme/app_theme.dart'; +import '../../models/pedido.dart'; + +class PedidoDetailScreen extends StatelessWidget { + final Pedido pedido; + + const PedidoDetailScreen({Key? key, required this.pedido}) : super(key: key); + + @override + Widget build(BuildContext context) { + final provider = context.read(); + final fmt = NumberFormat.currency(locale: 'es_BO', symbol: 'Bs.', decimalDigits: 2); + final estadoColor = AppTheme.estadoColor(pedido.estado.label); + final dateStr = DateFormat('d \'de\' MMMM yyyy, HH:mm', 'es').format(pedido.fecha); + + return Scaffold( + backgroundColor: AppTheme.bgColor, + appBar: AppBar( + title: Text(pedido.id, style: const TextStyle(fontWeight: FontWeight.bold)), + actions: [ + PopupMenuButton( + icon: const Icon(Icons.more_vert), + itemBuilder: (_) => EstadoPedido.values.map((e) { + return PopupMenuItem( + value: e, + child: Text(e.label), + ); + }).toList(), + onSelected: (estado) { + provider.cambiarEstadoPedido(pedido.id, estado); + Navigator.pop(context); + }, + ), + ], + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header card + _buildHeaderCard(estadoColor, dateStr), + const SizedBox(height: 14), + // Cliente + _buildClienteCard(), + const SizedBox(height: 14), + // Productos + _buildProductosCard(fmt), + const SizedBox(height: 14), + // Totals + _buildTotalesCard(fmt), + if (pedido.notas.isNotEmpty) ...[ + const SizedBox(height: 14), + _buildNotasCard(), + ], + if (pedido.firmaBase64 != null) ...[ + const SizedBox(height: 14), + _buildFirmaCard(), + ], + const SizedBox(height: 80), + ], + ), + ), + bottomNavigationBar: _buildBottomBar(context, provider, estadoColor, fmt), + ); + } + + Widget _buildHeaderCard(Color estadoColor, String dateStr) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: estadoColor.withOpacity(0.08), + borderRadius: BorderRadius.circular(14), + border: Border.all(color: estadoColor.withOpacity(0.3)), + ), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: estadoColor.withOpacity(0.15), + borderRadius: BorderRadius.circular(10), + ), + child: Icon(Icons.receipt_long, color: estadoColor, size: 28), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(pedido.id, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18, color: AppTheme.textPrimary)), + const SizedBox(height: 3), + Text(dateStr, style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: estadoColor, + borderRadius: BorderRadius.circular(20), + ), + child: Text( + pedido.estado.label, + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12), + ), + ), + ], + ), + ); + } + + Widget _buildClienteCard() { + return _sectionCard( + title: 'Cliente', + icon: Icons.store_outlined, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(pedido.cliente.nombre, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15, color: AppTheme.textPrimary)), + const SizedBox(height: 4), + Text(pedido.cliente.razonSocial, + style: const TextStyle(fontSize: 13, color: AppTheme.textSecondary)), + const SizedBox(height: 8), + _infoRow(Icons.location_on_outlined, pedido.cliente.direccion), + const SizedBox(height: 4), + _infoRow(Icons.phone_outlined, pedido.cliente.telefono), + const SizedBox(height: 4), + _infoRow(Icons.badge_outlined, 'NIT: ${pedido.cliente.nit}'), + ], + ), + ); + } + + Widget _buildProductosCard(NumberFormat fmt) { + return _sectionCard( + title: 'Productos (${pedido.items.length})', + icon: Icons.inventory_2_outlined, + child: Column( + children: pedido.items.map((item) => Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Row( + children: [ + Text(item.producto.emoji, style: const TextStyle(fontSize: 22)), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(item.producto.nombre, + style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), + Text('${fmt.format(item.precioUnitario)} × ${item.cantidad} ${item.producto.unidad}', + style: const TextStyle(fontSize: 11, color: AppTheme.textSecondary)), + ], + ), + ), + Text( + fmt.format(item.subtotal), + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: AppTheme.textPrimary), + ), + ], + ), + )).toList(), + ), + ); + } + + Widget _buildTotalesCard(NumberFormat fmt) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: AppTheme.primaryColor, + borderRadius: BorderRadius.circular(14), + ), + child: Column( + children: [ + _totalRow('Subtotal', fmt.format(pedido.subtotal), Colors.white70, Colors.white), + const SizedBox(height: 8), + _totalRow('Descuento', '0%', Colors.white70, Colors.white), + const Divider(color: Colors.white24, height: 20), + _totalRow('TOTAL', fmt.format(pedido.total), Colors.white, Colors.white, + isTotal: true), + ], + ), + ); + } + + Widget _totalRow(String label, String valor, Color labelColor, Color valueColor, {bool isTotal = false}) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(label, style: TextStyle(color: labelColor, fontSize: isTotal ? 16 : 13, fontWeight: isTotal ? FontWeight.bold : FontWeight.normal)), + Text(valor, style: TextStyle(color: valueColor, fontSize: isTotal ? 20 : 13, fontWeight: FontWeight.bold)), + ], + ); + } + + Widget _buildNotasCard() { + return _sectionCard( + title: 'Notas', + icon: Icons.notes_outlined, + child: Text(pedido.notas, style: const TextStyle(fontSize: 13, color: AppTheme.textPrimary)), + ); + } + + Widget _buildFirmaCard() { + return _sectionCard( + title: 'Firma del cliente', + icon: Icons.draw_outlined, + child: Container( + height: 100, + width: double.infinity, + decoration: BoxDecoration( + color: AppTheme.bgColor, + borderRadius: BorderRadius.circular(8), + ), + child: Center( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: const [ + Icon(Icons.check_circle, color: AppTheme.successColor, size: 20), + SizedBox(width: 8), + Text('Pedido firmado', style: TextStyle(color: AppTheme.successColor, fontWeight: FontWeight.w600)), + ], + ), + ), + ), + ); + } + + Widget _buildBottomBar(BuildContext context, AppProvider provider, Color estadoColor, NumberFormat fmt) { + return Container( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 24), + decoration: const BoxDecoration( + color: Colors.white, + boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 8, offset: Offset(0, -2))], + ), + child: Row( + children: [ + Expanded( + child: OutlinedButton.icon( + icon: const Icon(Icons.print_outlined), + label: const Text('Imprimir'), + onPressed: () {}, + ), + ), + const SizedBox(width: 12), + Expanded( + child: OutlinedButton.icon( + icon: const Icon(Icons.share_outlined), + label: const Text('Compartir'), + onPressed: () {}, + ), + ), + if (pedido.estado == EstadoPedido.confirmado) ...[ + const SizedBox(width: 12), + Expanded( + child: ElevatedButton.icon( + icon: const Icon(Icons.local_shipping_outlined, size: 18), + label: const Text('Marcar entregado', style: TextStyle(fontSize: 12)), + onPressed: () { + provider.cambiarEstadoPedido(pedido.id, EstadoPedido.entregado); + Navigator.pop(context); + }, + ), + ), + ], + ], + ), + ); + } + + Widget _sectionCard({required String title, required IconData icon, required Widget child}) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6)], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(icon, size: 17, color: AppTheme.primaryColor), + const SizedBox(width: 6), + Text(title, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: AppTheme.textPrimary)), + ], + ), + const Divider(height: 16), + child, + ], + ), + ); + } + + Widget _infoRow(IconData icon, String text) { + return Row( + children: [ + Icon(icon, size: 14, color: AppTheme.textSecondary), + const SizedBox(width: 6), + Expanded( + child: Text(text, style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + ), + ], + ); + } +} diff --git a/lib/screens/pedidos/pedido_form_screen.dart b/lib/screens/pedidos/pedido_form_screen.dart new file mode 100644 index 0000000..6eaf5d5 --- /dev/null +++ b/lib/screens/pedidos/pedido_form_screen.dart @@ -0,0 +1,515 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../../providers/app_provider.dart'; +import '../../theme/app_theme.dart'; +import '../../models/cliente.dart'; +import '../firma/firma_screen.dart'; +import '../scanner/scanner_helper.dart'; +import '../clientes/cliente_selector_screen.dart'; + +class PedidoFormScreen extends StatefulWidget { + const PedidoFormScreen({Key? key}) : super(key: key); + + @override + State createState() => _PedidoFormScreenState(); +} + +class _PedidoFormScreenState extends State { + final _notasCtrl = TextEditingController(); + final _searchCtrl = TextEditingController(); + String _productoQuery = ''; + bool _showSearch = false; + + final _fmt = NumberFormat.currency(locale: 'es_BO', symbol: 'Bs.', decimalDigits: 2); + + @override + void initState() { + super.initState(); + final provider = context.read(); + _notasCtrl.text = provider.notasPedido; + } + + @override + void dispose() { + _notasCtrl.dispose(); + _searchCtrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final provider = context.watch(); + + return Scaffold( + backgroundColor: AppTheme.bgColor, + appBar: AppBar( + title: const Text('Nuevo Pedido', style: TextStyle(fontWeight: FontWeight.bold)), + actions: [ + IconButton( + icon: const Icon(Icons.delete_outline), + onPressed: () { + showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text('Cancelar pedido'), + content: const Text('¿Descartar el pedido en curso?'), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('No')), + TextButton( + onPressed: () { + provider.limpiarCarrito(); + Navigator.pop(context); + Navigator.pop(context); + }, + child: const Text('Sí, descartar', style: TextStyle(color: AppTheme.dangerColor)), + ), + ], + ), + ); + }, + ), + ], + ), + body: Column( + children: [ + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildClienteSection(context, provider), + const SizedBox(height: 16), + _buildProductoSearch(context, provider), + if (_showSearch) _buildSearchResults(context, provider), + const SizedBox(height: 16), + _buildCarrito(context, provider), + const SizedBox(height: 16), + _buildNotasSection(context, provider), + const SizedBox(height: 80), + ], + ), + ), + ), + _buildBottomBar(context, provider), + ], + ), + ); + } + + Widget _buildClienteSection(BuildContext context, AppProvider provider) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Cliente', style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: AppTheme.textPrimary)), + const SizedBox(height: 8), + if (provider.clienteSeleccionado != null) + _buildClienteCard(provider.clienteSeleccionado!) + else + _buildClienteSelector(context, provider), + ], + ); + } + + Widget _buildClienteCard(Cliente cliente) { + return Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: AppTheme.primaryColor.withOpacity(0.3)), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6)], + ), + child: Row( + children: [ + Container( + width: 44, + height: 44, + decoration: BoxDecoration( + color: AppTheme.primaryColor.withOpacity(0.1), + borderRadius: BorderRadius.circular(10), + ), + child: const Icon(Icons.store, color: AppTheme.primaryColor, size: 24), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(cliente.nombre, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + Text(cliente.direccion, style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary), maxLines: 1, overflow: TextOverflow.ellipsis), + Text('NIT: ${cliente.nit}', style: const TextStyle(fontSize: 11, color: AppTheme.textSecondary)), + ], + ), + ), + const Icon(Icons.check_circle, color: AppTheme.successColor, size: 22), + ], + ), + ); + } + + Widget _buildClienteSelector(BuildContext context, AppProvider provider) { + return Material( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + elevation: 1, + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: () => _abrirSelectorCliente(context, provider), + child: Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + border: Border.all(color: const Color(0xFFCBD5E1)), + borderRadius: BorderRadius.circular(12), + ), + child: Row( + children: const [ + Icon(Icons.store_outlined, color: AppTheme.textSecondary), + SizedBox(width: 12), + Text('Seleccionar cliente...', style: TextStyle(color: AppTheme.textSecondary)), + Spacer(), + Icon(Icons.arrow_drop_down, color: AppTheme.textSecondary), + ], + ), + ), + ), + ); + } + + Future _abrirSelectorCliente(BuildContext context, AppProvider provider) async { + final cliente = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ClienteSelectorScreen(clientes: provider.clientes), + ), + ); + if (cliente != null) provider.seleccionarCliente(cliente); + } + + Widget _buildProductoSearch(BuildContext context, AppProvider provider) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Agregar productos', style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: AppTheme.textPrimary)), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: TextField( + controller: _searchCtrl, + onTap: () => setState(() => _showSearch = true), + onChanged: (v) => setState(() => _productoQuery = v), + decoration: InputDecoration( + hintText: 'Buscar producto o SKU...', + prefixIcon: const Icon(Icons.search), + suffixIcon: _showSearch + ? IconButton( + icon: const Icon(Icons.close), + onPressed: () { + _searchCtrl.clear(); + setState(() { + _productoQuery = ''; + _showSearch = false; + }); + }, + ) + : null, + ), + ), + ), + const SizedBox(width: 8), + Material( + color: AppTheme.primaryColor, + borderRadius: BorderRadius.circular(10), + child: InkWell( + borderRadius: BorderRadius.circular(10), + onTap: () async { + final resultado = await abrirScanner(context, titulo: 'Escanear producto'); + if (resultado == null || !mounted) return; + final coincidencias = provider.productos.where( + (p) => p.sku.toLowerCase() == resultado.toLowerCase() || + p.nombre.toLowerCase().contains(resultado.toLowerCase()), + ).toList(); + final producto = coincidencias.isEmpty ? null : coincidencias.first; + if (producto != null) { + provider.agregarAlCarrito(producto); + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text('${producto.nombre} agregado al pedido'), + backgroundColor: AppTheme.successColor, + duration: const Duration(seconds: 2), + )); + } else { + // Si no coincide exacto, poner en el campo de búsqueda + _searchCtrl.text = resultado; + setState(() { + _productoQuery = resultado; + _showSearch = true; + }); + } + }, + child: const Padding( + padding: EdgeInsets.all(14), + child: Icon(Icons.qr_code_scanner, color: Colors.white, size: 22), + ), + ), + ), + ], + ), + ], + ); + } + + Widget _buildSearchResults(BuildContext context, AppProvider provider) { + final results = provider.productos.where((p) { + if (_productoQuery.isEmpty) return true; + return p.nombre.toLowerCase().contains(_productoQuery.toLowerCase()) || + p.sku.toLowerCase().contains(_productoQuery.toLowerCase()); + }).take(6).toList(); + + return Container( + margin: const EdgeInsets.only(top: 4), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.08), blurRadius: 8)], + ), + child: Column( + children: results.map((p) { + final enCarrito = provider.carrito.where((i) => i.producto.id == p.id); + final qty = enCarrito.isNotEmpty ? enCarrito.first.cantidad : 0; + return ListTile( + dense: true, + leading: Text(p.emoji, style: const TextStyle(fontSize: 24)), + title: Text(p.nombre, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), + subtitle: Text(_fmt.format(p.precio), style: const TextStyle(fontSize: 12, color: AppTheme.primaryColor)), + trailing: qty == 0 + ? IconButton( + icon: const Icon(Icons.add_circle, color: AppTheme.primaryColor), + onPressed: () => provider.agregarAlCarrito(p), + ) + : Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.remove_circle_outline, size: 20), + onPressed: () => provider.actualizarCantidad(p.id, qty - 1), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 6), + child: Text('$qty', style: const TextStyle(fontWeight: FontWeight.bold)), + ), + IconButton( + icon: const Icon(Icons.add_circle, size: 20, color: AppTheme.primaryColor), + onPressed: () => provider.agregarAlCarrito(p), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + ), + ], + ), + ); + }).toList(), + ), + ); + } + + Widget _buildCarrito(BuildContext context, AppProvider provider) { + if (provider.carrito.isEmpty) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 32), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFE2E8F0), style: BorderStyle.solid), + ), + child: Center( + child: Column( + children: const [ + Icon(Icons.shopping_cart_outlined, size: 40, color: AppTheme.textSecondary), + SizedBox(height: 8), + Text('Carrito vacío', style: TextStyle(color: AppTheme.textSecondary)), + Text('Busca y agrega productos arriba', style: TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + ], + ), + ), + ); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('Carrito (${provider.carrito.length} productos)', + style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: AppTheme.textPrimary)), + TextButton.icon( + icon: const Icon(Icons.delete_outline, size: 16), + label: const Text('Limpiar', style: TextStyle(fontSize: 12)), + onPressed: provider.limpiarCarrito, + style: TextButton.styleFrom(primary: AppTheme.dangerColor), + ), + ], + ), + const SizedBox(height: 8), + Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6)], + ), + child: Column( + children: [ + ...provider.carrito.map((item) => Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + decoration: BoxDecoration( + border: Border(bottom: BorderSide(color: Colors.grey.shade100)), + ), + child: Row( + children: [ + Text(item.producto.emoji, style: const TextStyle(fontSize: 20)), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(item.producto.nombre, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), + Text('${_fmt.format(item.precioUnitario)} x ${item.cantidad}', + style: const TextStyle(fontSize: 11, color: AppTheme.textSecondary)), + ], + ), + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + _counterBtn(Icons.remove, () => provider.actualizarCantidad(item.producto.id, item.cantidad - 1)), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 10), + child: Text('${item.cantidad}', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + ), + _counterBtn(Icons.add, () => provider.agregarAlCarrito(item.producto)), + ], + ), + const SizedBox(width: 8), + Text( + _fmt.format(item.subtotal), + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: AppTheme.primaryColor), + ), + IconButton( + icon: const Icon(Icons.close, size: 16, color: AppTheme.textSecondary), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + onPressed: () => provider.quitarDelCarrito(item.producto.id), + ), + ], + ), + )).toList(), + // Totals + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: AppTheme.primaryColor.withOpacity(0.04), + borderRadius: const BorderRadius.vertical(bottom: Radius.circular(12)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('${provider.cantidadCarrito} unidades', style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + const Text('Total a pagar:', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), + ], + ), + Text( + _fmt.format(provider.totalCarrito), + style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: AppTheme.primaryColor), + ), + ], + ), + ), + ], + ), + ), + ], + ); + } + + Widget _buildNotasSection(BuildContext context, AppProvider provider) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Notas del pedido', style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: AppTheme.textPrimary)), + const SizedBox(height: 8), + TextField( + controller: _notasCtrl, + onChanged: provider.setNotasPedido, + maxLines: 3, + decoration: const InputDecoration( + hintText: 'Instrucciones especiales, horario de entrega...', + alignLabelWithHint: true, + ), + ), + ], + ); + } + + Widget _buildBottomBar(BuildContext context, AppProvider provider) { + final canConfirm = provider.clienteSeleccionado != null && provider.carrito.isNotEmpty; + + return Container( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 24), + decoration: BoxDecoration( + color: Colors.white, + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.08), blurRadius: 12, offset: const Offset(0, -4))], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Total del pedido:', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500)), + Text( + _fmt.format(provider.totalCarrito), + style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: AppTheme.primaryColor), + ), + ], + ), + const SizedBox(height: 12), + SizedBox( + width: double.infinity, + height: 52, + child: ElevatedButton.icon( + icon: const Icon(Icons.draw_outlined, size: 22), + label: const Text('Confirmar y Firmar', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)), + onPressed: canConfirm + ? () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const FirmaScreen()), + ) + : null, + ), + ), + ], + ), + ); + } + + Widget _counterBtn(IconData icon, VoidCallback onTap) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(4), + child: Container( + padding: const EdgeInsets.all(3), + decoration: BoxDecoration( + color: AppTheme.primaryColor.withOpacity(0.1), + borderRadius: BorderRadius.circular(4), + ), + child: Icon(icon, size: 16, color: AppTheme.primaryColor), + ), + ); + } +} diff --git a/lib/screens/pedidos/pedidos_screen.dart b/lib/screens/pedidos/pedidos_screen.dart new file mode 100644 index 0000000..d350a9b --- /dev/null +++ b/lib/screens/pedidos/pedidos_screen.dart @@ -0,0 +1,279 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../../providers/app_provider.dart'; +import '../../theme/app_theme.dart'; +import '../../models/pedido.dart'; +import 'pedido_form_screen.dart'; +import 'pedido_detail_screen.dart'; + +class PedidosScreen extends StatefulWidget { + const PedidosScreen({Key? key}) : super(key: key); + + @override + State createState() => _PedidosScreenState(); +} + +class _PedidosScreenState extends State with SingleTickerProviderStateMixin { + late TabController _tab; + final _fmt = NumberFormat.currency(locale: 'es_BO', symbol: 'Bs.', decimalDigits: 2); + + @override + void initState() { + super.initState(); + _tab = TabController(length: 4, vsync: this); + } + + @override + void dispose() { + _tab.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final provider = context.watch(); + + return Scaffold( + backgroundColor: AppTheme.bgColor, + appBar: AppBar( + title: const Text('Pedidos', style: TextStyle(fontWeight: FontWeight.bold)), + actions: [ + IconButton(icon: const Icon(Icons.search), onPressed: () {}), + IconButton(icon: const Icon(Icons.filter_list), onPressed: () {}), + ], + bottom: TabBar( + controller: _tab, + indicatorColor: Colors.white, + indicatorWeight: 3, + isScrollable: true, + tabs: _buildTabs(provider), + ), + ), + body: TabBarView( + controller: _tab, + children: [ + _buildList(context, provider.pedidos, provider), + _buildList( + context, + provider.pedidos.where((p) => p.estado == EstadoPedido.pendiente).toList(), + provider), + _buildList( + context, + provider.pedidos.where((p) => p.estado == EstadoPedido.confirmado).toList(), + provider), + _buildList( + context, + provider.pedidos.where((p) => p.estado == EstadoPedido.entregado).toList(), + provider), + ], + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: () { + Navigator.push( + context, + MaterialPageRoute(builder: (_) => const PedidoFormScreen()), + ); + }, + icon: const Icon(Icons.add), + label: const Text('Nuevo pedido'), + backgroundColor: AppTheme.primaryColor, + ), + ); + } + + List _buildTabs(AppProvider provider) { + final todos = provider.pedidos.length; + final pend = provider.pedidos.where((p) => p.estado == EstadoPedido.pendiente).length; + final conf = provider.pedidos.where((p) => p.estado == EstadoPedido.confirmado).length; + final entr = provider.pedidos.where((p) => p.estado == EstadoPedido.entregado).length; + + return [ + Tab(text: 'Todos ($todos)'), + Tab(text: 'Pendiente ($pend)'), + Tab(text: 'Confirmado ($conf)'), + Tab(text: 'Entregado ($entr)'), + ]; + } + + Widget _buildList(BuildContext context, List pedidos, AppProvider provider) { + if (pedidos.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.receipt_long_outlined, size: 64, color: Colors.grey.shade300), + const SizedBox(height: 12), + const Text('No hay pedidos', style: TextStyle(color: AppTheme.textSecondary, fontSize: 15)), + ], + ), + ); + } + + return ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 80), + itemCount: pedidos.length, + itemBuilder: (context, i) => _buildPedidoCard(context, pedidos[i], provider), + ); + } + + Widget _buildPedidoCard(BuildContext context, Pedido pedido, AppProvider provider) { + final estadoColor = AppTheme.estadoColor(pedido.estado.label); + final timeStr = DateFormat('d MMM, HH:mm', 'es').format(pedido.fecha); + + return Dismissible( + key: Key(pedido.id), + direction: DismissDirection.endToStart, + background: Container( + alignment: Alignment.centerRight, + padding: const EdgeInsets.only(right: 20), + decoration: BoxDecoration( + color: AppTheme.dangerColor, + borderRadius: BorderRadius.circular(14), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: const [ + Icon(Icons.delete_outline, color: Colors.white, size: 28), + SizedBox(height: 4), + Text('Eliminar', style: TextStyle(color: Colors.white, fontSize: 11)), + ], + ), + ), + confirmDismiss: (dir) async { + return await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Eliminar pedido'), + content: Text('¿Eliminar el pedido ${pedido.id}?'), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancelar')), + TextButton( + onPressed: () => Navigator.pop(ctx, true), + child: const Text('Eliminar', style: TextStyle(color: AppTheme.dangerColor)), + ), + ], + ), + ) ?? false; + }, + onDismissed: (_) => provider.eliminarPedido(pedido.id), + child: GestureDetector( + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => PedidoDetailScreen(pedido: pedido)), + ), + child: Container( + margin: const EdgeInsets.only(bottom: 10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: estadoColor.withOpacity(0.2)), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6, offset: const Offset(0, 2))], + ), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: estadoColor.withOpacity(0.1), + borderRadius: BorderRadius.circular(8), + ), + child: Icon(Icons.receipt_outlined, color: estadoColor, size: 20), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + pedido.id, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: AppTheme.textPrimary), + ), + Text(timeStr, style: const TextStyle(fontSize: 11, color: AppTheme.textSecondary)), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: estadoColor.withOpacity(0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + pedido.estado.label, + style: TextStyle(fontSize: 11, color: estadoColor, fontWeight: FontWeight.w700), + ), + ), + ], + ), + const Divider(height: 16), + Row( + children: [ + const Icon(Icons.store_outlined, size: 14, color: AppTheme.textSecondary), + const SizedBox(width: 4), + Expanded( + child: Text( + pedido.cliente.nombre, + style: const TextStyle(fontSize: 13, color: AppTheme.textPrimary, fontWeight: FontWeight.w500), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + const SizedBox(height: 6), + Row( + children: [ + const Icon(Icons.inventory_2_outlined, size: 14, color: AppTheme.textSecondary), + const SizedBox(width: 4), + Text( + '${pedido.totalItems} productos · ${pedido.items.length} líneas', + style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary), + ), + const Spacer(), + Text( + _fmt.format(pedido.total), + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: AppTheme.primaryColor, + ), + ), + ], + ), + if (pedido.notas.isNotEmpty) ...[ + const SizedBox(height: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: AppTheme.bgColor, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + const Icon(Icons.notes, size: 13, color: AppTheme.textSecondary), + const SizedBox(width: 6), + Expanded( + child: Text( + pedido.notas, + style: const TextStyle(fontSize: 11, color: AppTheme.textSecondary), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ], + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/screens/perfil/perfil_screen.dart b/lib/screens/perfil/perfil_screen.dart new file mode 100644 index 0000000..8814cfb --- /dev/null +++ b/lib/screens/perfil/perfil_screen.dart @@ -0,0 +1,337 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../../providers/app_provider.dart'; +import '../../theme/app_theme.dart'; +import '../../models/pedido.dart'; + +class PerfilScreen extends StatelessWidget { + const PerfilScreen({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + final provider = context.watch(); + final vendedor = provider.vendedor; + final fmt = NumberFormat.currency(locale: 'es_BO', symbol: 'Bs.', decimalDigits: 2); + + return Scaffold( + backgroundColor: AppTheme.bgColor, + body: CustomScrollView( + slivers: [ + _buildSliverHeader(context, vendedor, provider), + SliverPadding( + padding: const EdgeInsets.all(16), + sliver: SliverList( + delegate: SliverChildListDelegate([ + _buildStatsRow(provider, fmt), + const SizedBox(height: 20), + _buildRutaProgress(provider), + const SizedBox(height: 20), + _buildPedidosResumen(context, provider, fmt), + const SizedBox(height: 20), + _buildInfoCard(vendedor), + const SizedBox(height: 20), + _buildConfigSection(context), + const SizedBox(height: 20), + _buildLogoutBtn(context, provider), + const SizedBox(height: 40), + ]), + ), + ), + ], + ), + ); + } + + Widget _buildSliverHeader(BuildContext context, vendedor, AppProvider provider) { + return SliverAppBar( + expandedHeight: 200, + pinned: true, + backgroundColor: AppTheme.primaryColor, + flexibleSpace: FlexibleSpaceBar( + background: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + colors: [Color(0xFF1E3A8A), Color(0xFF2563EB)], + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + ), + ), + child: SafeArea( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircleAvatar( + radius: 40, + backgroundColor: Colors.white.withOpacity(0.2), + child: Text( + vendedor.avatarInitials, + style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: Colors.white), + ), + ), + const SizedBox(height: 10), + Text(vendedor.nombre, + style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white)), + const SizedBox(height: 4), + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.2), + borderRadius: BorderRadius.circular(12), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.location_on, color: Colors.white70, size: 14), + const SizedBox(width: 4), + Text(vendedor.zona, + style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w500)), + ], + ), + ), + ], + ), + ), + ), + title: Text(vendedor.nombre, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + titlePadding: const EdgeInsets.only(left: 16, bottom: 12), + ), + ); + } + + Widget _buildStatsRow(AppProvider provider, NumberFormat fmt) { + final stats = [ + {'label': 'Pedidos hoy', 'value': '${provider.pedidosHoy}', 'color': AppTheme.primaryColor}, + {'label': 'Ventas hoy', 'value': fmt.format(provider.ventasTotalesHoy), 'color': AppTheme.successColor}, + { + 'label': 'Clientes', + 'value': '${provider.ruta.visitadas}/${provider.ruta.paradas.length}', + 'color': AppTheme.accentColor + }, + ]; + + return Row( + children: stats.map((s) { + final color = s['color'] as Color; + return Expanded( + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 4), + padding: const EdgeInsets.symmetric(vertical: 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [BoxShadow(color: color.withOpacity(0.1), blurRadius: 8)], + ), + child: Column( + children: [ + Text(s['value'] as String, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: color)), + const SizedBox(height: 4), + Text(s['label'] as String, + style: const TextStyle(fontSize: 10, color: AppTheme.textSecondary), textAlign: TextAlign.center), + ], + ), + ), + ); + }).toList(), + ); + } + + Widget _buildRutaProgress(AppProvider provider) { + final ruta = provider.ruta; + final progress = ruta.paradas.isEmpty ? 0.0 : ruta.visitadas / ruta.paradas.length; + + return _card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Progreso de ruta', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + Text('${(progress * 100).toInt()}% completado', + style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + ], + ), + const SizedBox(height: 12), + ClipRRect( + borderRadius: BorderRadius.circular(6), + child: LinearProgressIndicator( + value: progress, + backgroundColor: AppTheme.bgColor, + valueColor: AlwaysStoppedAnimation( + progress == 1.0 ? AppTheme.successColor : AppTheme.primaryColor, + ), + minHeight: 10, + ), + ), + const SizedBox(height: 10), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + _progressChip(Icons.check_circle, '${ruta.visitadas} visitadas', AppTheme.successColor), + _progressChip(Icons.pending, '${ruta.pendientes} pendientes', AppTheme.warningColor), + _progressChip(Icons.location_on, '${ruta.paradas.length} total', AppTheme.primaryColor), + ], + ), + ], + ), + ); + } + + Widget _progressChip(IconData icon, String label, Color color) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 14, color: color), + const SizedBox(width: 4), + Text(label, style: TextStyle(fontSize: 11, color: color, fontWeight: FontWeight.w500)), + ], + ); + } + + Widget _buildPedidosResumen(BuildContext context, AppProvider provider, NumberFormat fmt) { + final estados = { + EstadoPedido.confirmado: provider.pedidos.where((p) => p.estado == EstadoPedido.confirmado).length, + EstadoPedido.entregado: provider.pedidos.where((p) => p.estado == EstadoPedido.entregado).length, + EstadoPedido.pendiente: provider.pedidos.where((p) => p.estado == EstadoPedido.pendiente).length, + EstadoPedido.cancelado: provider.pedidos.where((p) => p.estado == EstadoPedido.cancelado).length, + }; + + return _card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Resumen de pedidos', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + const SizedBox(height: 12), + ...estados.entries.map((e) { + final color = AppTheme.estadoColor(e.key.label); + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + children: [ + Container(width: 10, height: 10, decoration: BoxDecoration(color: color, shape: BoxShape.circle)), + const SizedBox(width: 10), + Text(e.key.label, style: const TextStyle(fontSize: 13)), + const Spacer(), + Text('${e.value}', style: TextStyle(fontWeight: FontWeight.bold, color: color)), + ], + ), + ); + }).toList(), + ], + ), + ); + } + + Widget _buildInfoCard(vendedor) { + return _card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Información de contacto', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + const SizedBox(height: 12), + _infoTile(Icons.email_outlined, 'Correo', vendedor.email), + _infoTile(Icons.phone_outlined, 'Teléfono', vendedor.telefono), + _infoTile(Icons.map_outlined, 'Zona', vendedor.zona), + ], + ), + ); + } + + Widget _infoTile(IconData icon, String label, String value) { + return Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Row( + children: [ + Icon(icon, size: 18, color: AppTheme.primaryColor), + const SizedBox(width: 10), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, style: const TextStyle(fontSize: 10, color: AppTheme.textSecondary)), + Text(value, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), + ], + ), + ], + ), + ); + } + + Widget _buildConfigSection(BuildContext context) { + final opciones = [ + {'icon': Icons.notifications_outlined, 'label': 'Notificaciones', 'trailing': true}, + {'icon': Icons.language, 'label': 'Idioma', 'value': 'Español'}, + {'icon': Icons.help_outline, 'label': 'Ayuda y soporte', 'arrow': true}, + {'icon': Icons.info_outline, 'label': 'Acerca de la app', 'value': 'v1.0.0'}, + ]; + + return _card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Configuración', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + const SizedBox(height: 8), + ...opciones.map((o) => ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + leading: Icon(o['icon'] as IconData, color: AppTheme.primaryColor, size: 22), + title: Text(o['label'] as String, style: const TextStyle(fontSize: 13)), + trailing: o['trailing'] == true + ? Switch(value: true, onChanged: (_) {}, activeColor: AppTheme.primaryColor) + : o['arrow'] == true + ? const Icon(Icons.chevron_right, color: AppTheme.textSecondary) + : Text(o['value'] as String? ?? '', style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + onTap: () {}, + )).toList(), + ], + ), + ); + } + + Widget _buildLogoutBtn(BuildContext context, AppProvider provider) { + return SizedBox( + width: double.infinity, + height: 50, + child: OutlinedButton.icon( + icon: const Icon(Icons.logout, color: AppTheme.dangerColor), + label: const Text('Cerrar sesión', style: TextStyle(color: AppTheme.dangerColor, fontWeight: FontWeight.w600)), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: AppTheme.dangerColor), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + onPressed: () { + showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text('Cerrar sesión'), + content: const Text('¿Seguro que deseas salir?'), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancelar')), + TextButton( + onPressed: () { + Navigator.pop(context); + provider.logout(); + }, + child: const Text('Salir', style: TextStyle(color: AppTheme.dangerColor)), + ), + ], + ), + ); + }, + ), + ); + } + + Widget _card({required Widget child}) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6)], + ), + child: child, + ); + } +} diff --git a/lib/screens/rutas/rutas_screen.dart b/lib/screens/rutas/rutas_screen.dart new file mode 100644 index 0000000..9d4d689 --- /dev/null +++ b/lib/screens/rutas/rutas_screen.dart @@ -0,0 +1,840 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../../providers/app_provider.dart'; +import '../../theme/app_theme.dart'; +import '../../models/cliente.dart'; +import '../../models/parada_ruta.dart'; +import '../../widgets/route_map_painter.dart'; +import '../clientes/cliente_form_screen.dart'; +import '../pedidos/pedido_form_screen.dart'; + +class RutasScreen extends StatefulWidget { + const RutasScreen({Key? key}) : super(key: key); + + @override + State createState() => _RutasScreenState(); +} + +class _RutasScreenState extends State with SingleTickerProviderStateMixin { + late TabController _tabController; + + @override + void initState() { + super.initState(); + _tabController = TabController(length: 2, vsync: this); + } + + @override + void dispose() { + _tabController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final provider = context.watch(); + final ruta = provider.ruta; + + return Scaffold( + backgroundColor: AppTheme.bgColor, + appBar: AppBar( + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Ruta del Día', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 17)), + Text(ruta.zona, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.normal, color: Colors.white70)), + ], + ), + actions: [ + Padding( + padding: const EdgeInsets.only(right: 8), + child: Chip( + label: Text( + '${ruta.visitadas}/${ruta.paradas.length}', + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12), + ), + backgroundColor: Colors.white.withOpacity(0.2), + padding: EdgeInsets.zero, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ), + ], + bottom: TabBar( + controller: _tabController, + indicatorColor: Colors.white, + indicatorWeight: 3, + tabs: const [ + Tab(icon: Icon(Icons.map_outlined, size: 18), text: 'Mapa'), + Tab(icon: Icon(Icons.list_alt, size: 18), text: 'Paradas'), + ], + ), + ), + body: TabBarView( + controller: _tabController, + children: [ + _buildMapView(context, provider), + _buildListView(context, provider), + ], + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: () => _showAgregarParadaSheet(context, provider), + icon: const Icon(Icons.add_location_alt_outlined), + label: const Text('Agregar parada'), + backgroundColor: AppTheme.accentColor, + ), + ); + } + + Widget _buildMapView(BuildContext context, AppProvider provider) { + final ruta = provider.ruta; + return Column( + children: [ + Expanded( + flex: 3, + child: Container( + margin: const EdgeInsets.all(16), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(16), + boxShadow: [ + BoxShadow(color: Colors.black.withOpacity(0.1), blurRadius: 12, offset: const Offset(0, 4)), + ], + ), + clipBehavior: Clip.antiAlias, + child: Stack( + children: [ + CustomPaint( + painter: RouteMapPainter(ruta.paradas), + child: const SizedBox.expand(), + ), + // Map legend + Positioned( + top: 12, + right: 12, + child: _buildLegend(), + ), + // Controls + Positioned( + bottom: 12, + right: 12, + child: Column( + children: [ + _mapButton(Icons.add, () {}), + const SizedBox(height: 8), + _mapButton(Icons.remove, () {}), + const SizedBox(height: 8), + _mapButton(Icons.my_location, () {}), + ], + ), + ), + ], + ), + ), + ), + Expanded( + flex: 2, + child: ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), + itemCount: ruta.paradas.length, + itemBuilder: (context, i) => _buildParadaMini(context, ruta.paradas[i], provider), + ), + ), + ], + ); + } + + Widget _buildLegend() { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.92), + borderRadius: BorderRadius.circular(8), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.1), blurRadius: 4)], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _legendItem(AppTheme.successColor, 'Visitado'), + const SizedBox(height: 4), + _legendItem(AppTheme.accentColor, 'Actual'), + const SizedBox(height: 4), + _legendItem(AppTheme.primaryColor.withOpacity(0.5), 'Pendiente'), + const SizedBox(height: 4), + _legendItem(Colors.blue, 'Mi ubicación'), + ], + ), + ); + } + + Widget _legendItem(Color color, String label) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container(width: 10, height: 10, decoration: BoxDecoration(color: color, shape: BoxShape.circle)), + const SizedBox(width: 6), + Text(label, style: const TextStyle(fontSize: 10, color: AppTheme.textPrimary)), + ], + ); + } + + Widget _mapButton(IconData icon, VoidCallback onTap) { + return Material( + color: Colors.white, + elevation: 2, + borderRadius: BorderRadius.circular(8), + child: InkWell( + borderRadius: BorderRadius.circular(8), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.all(8), + child: Icon(icon, size: 20, color: AppTheme.primaryColor), + ), + ), + ); + } + + Widget _buildParadaMini(BuildContext context, ParadaRuta parada, AppProvider provider) { + final isVisited = parada.estado == EstadoParada.visitado; + final color = isVisited ? AppTheme.successColor : AppTheme.primaryColor; + + return Container( + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: color.withOpacity(0.3)), + ), + child: Row( + children: [ + CircleAvatar( + radius: 14, + backgroundColor: color.withOpacity(0.15), + child: Text('${parada.orden}', style: TextStyle(color: color, fontWeight: FontWeight.bold, fontSize: 12)), + ), + const SizedBox(width: 10), + Expanded( + child: Text( + parada.cliente.nombre, + style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500), + overflow: TextOverflow.ellipsis, + ), + ), + if (isVisited) + const Icon(Icons.check_circle, color: AppTheme.successColor, size: 18) + else + TextButton( + style: TextButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: 8), minimumSize: Size.zero), + onPressed: () => _tabController.animateTo(1), + child: const Text('Ir', style: TextStyle(fontSize: 12)), + ), + ], + ), + ); + } + + Widget _buildListView(BuildContext context, AppProvider provider) { + final ruta = provider.ruta; + return ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 90), + itemCount: ruta.paradas.length, + itemBuilder: (context, i) { + final parada = ruta.paradas[i]; + final puedeEliminar = parada.estado == EstadoParada.pendiente; + return Dismissible( + key: Key(parada.id), + direction: puedeEliminar ? DismissDirection.endToStart : DismissDirection.none, + background: Container( + alignment: Alignment.centerRight, + padding: const EdgeInsets.only(right: 20), + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + color: AppTheme.dangerColor, + borderRadius: BorderRadius.circular(14), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: const [ + Icon(Icons.delete_outline, color: Colors.white, size: 26), + SizedBox(height: 4), + Text('Quitar', style: TextStyle(color: Colors.white, fontSize: 11)), + ], + ), + ), + confirmDismiss: (_) async => await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Quitar parada'), + content: Text('¿Quitar a ${parada.cliente.nombre} de la ruta de hoy?'), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancelar')), + TextButton( + onPressed: () => Navigator.pop(ctx, true), + child: const Text('Quitar', style: TextStyle(color: AppTheme.dangerColor)), + ), + ], + ), + ) ?? false, + onDismissed: (_) { + provider.eliminarParada(parada.id); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('${parada.cliente.nombre} quitado de la ruta'), + behavior: SnackBarBehavior.floating, + ), + ); + }, + child: _buildParadaCard(context, parada, provider), + ); + }, + ); + } + + Widget _buildParadaCard(BuildContext context, ParadaRuta parada, AppProvider provider) { + final isVisited = parada.estado == EstadoParada.visitado; + final isSaltado = parada.estado == EstadoParada.saltado; + final color = isVisited + ? AppTheme.successColor + : isSaltado + ? AppTheme.dangerColor + : AppTheme.primaryColor; + + return Container( + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: color.withOpacity(0.25)), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6, offset: const Offset(0, 2))], + ), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.all(14), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: color.withOpacity(0.15), + shape: BoxShape.circle, + ), + child: isVisited + ? const Icon(Icons.check, color: AppTheme.successColor, size: 20) + : Center( + child: Text( + '${parada.orden}', + style: TextStyle(color: color, fontWeight: FontWeight.bold, fontSize: 14), + ), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + parada.cliente.nombre, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: AppTheme.textPrimary), + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: color.withOpacity(0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + isVisited ? 'Visitado' : isSaltado ? 'Saltado' : 'Pendiente', + style: TextStyle(fontSize: 10, color: color, fontWeight: FontWeight.w600), + ), + ), + ], + ), + const SizedBox(height: 3), + Row( + children: [ + const Icon(Icons.location_on_outlined, size: 13, color: AppTheme.textSecondary), + const SizedBox(width: 2), + Expanded( + child: Text( + parada.cliente.direccion, + style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + const SizedBox(height: 3), + Row( + children: [ + const Icon(Icons.access_time, size: 13, color: AppTheme.textSecondary), + const SizedBox(width: 2), + Text( + isVisited + ? 'Visitado a las ${parada.horaVisita}' + : 'Estimado: ${parada.horaEstimada}', + style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary), + ), + ], + ), + const SizedBox(height: 3), + Row( + children: [ + const Icon(Icons.category_outlined, size: 13, color: AppTheme.textSecondary), + const SizedBox(width: 2), + Text( + parada.cliente.categoria, + style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary), + ), + ], + ), + ], + ), + ), + ], + ), + ), + if (!isVisited && !isSaltado) + Padding( + padding: const EdgeInsets.fromLTRB(14, 0, 14, 14), + child: Row( + children: [ + Expanded( + child: OutlinedButton.icon( + icon: const Icon(Icons.phone, size: 16), + label: const Text('Llamar', style: TextStyle(fontSize: 13)), + onPressed: () {}, + style: OutlinedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 8), + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: OutlinedButton.icon( + icon: const Icon(Icons.directions, size: 16), + label: const Text('Navegar', style: TextStyle(fontSize: 13)), + onPressed: () {}, + style: OutlinedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 8), + ), + ), + ), + const SizedBox(width: 8), + Expanded( + flex: 2, + child: ElevatedButton.icon( + icon: const Icon(Icons.add_shopping_cart, size: 16), + label: const Text('Tomar pedido', style: TextStyle(fontSize: 12)), + onPressed: () { + provider.seleccionarCliente(parada.cliente); + provider.marcarParadaVisitada(parada.id); + Navigator.push( + context, + MaterialPageRoute(builder: (_) => const PedidoFormScreen()), + ); + }, + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 8), + ), + ), + ), + ], + ), + ), + ], + ), + ); + } + + void _showAgregarParadaSheet(BuildContext context, AppProvider provider) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + builder: (ctx) => _AgregarParadaSheet(provider: provider), + ); + } + +} + +// ───────────────────────────────────────────────────────── +// Bottom sheet: seleccionar cliente registrado O crear nuevo +// ───────────────────────────────────────────────────────── + +class _AgregarParadaSheet extends StatefulWidget { + final AppProvider provider; + const _AgregarParadaSheet({Key? key, required this.provider}) : super(key: key); + + @override + State<_AgregarParadaSheet> createState() => _AgregarParadaSheetState(); +} + +class _AgregarParadaSheetState extends State<_AgregarParadaSheet> + with SingleTickerProviderStateMixin { + late TabController _tab; + Cliente? _clienteElegido; + final _horaCtrl = TextEditingController(); + final _searchCtrl = TextEditingController(); + String _query = ''; + + @override + void initState() { + super.initState(); + _tab = TabController(length: 2, vsync: this); + final now = DateTime.now(); + final h = now.hour.toString().padLeft(2, '0'); + final m = ((now.minute ~/ 15 + 1) * 15 % 60).toString().padLeft(2, '0'); + _horaCtrl.text = '$h:$m'; + } + + @override + void dispose() { + _tab.dispose(); + _horaCtrl.dispose(); + _searchCtrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final todosDisponibles = widget.provider.clientesSinParada + .where((c) => _query.isEmpty || c.nombre.toLowerCase().contains(_query.toLowerCase()) || + c.nit.toLowerCase().contains(_query.toLowerCase())) + .toList(); + final hayMas = todosDisponibles.length > 50; + final disponibles = hayMas ? todosDisponibles.take(50).toList() : todosDisponibles; + + return DraggableScrollableSheet( + expand: false, + initialChildSize: 0.75, + minChildSize: 0.5, + maxChildSize: 0.95, + builder: (_, scrollCtrl) => Column( + children: [ + // Handle + header + Padding( + padding: const EdgeInsets.fromLTRB(20, 12, 20, 0), + child: Column( + children: [ + Center( + child: Container( + width: 40, height: 4, + decoration: BoxDecoration( + color: Colors.grey.shade300, + borderRadius: BorderRadius.circular(2), + ), + ), + ), + const SizedBox(height: 14), + Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: AppTheme.accentColor.withOpacity(0.12), + borderRadius: BorderRadius.circular(10), + ), + child: const Icon(Icons.add_location_alt, color: AppTheme.accentColor, size: 22), + ), + const SizedBox(width: 12), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: const [ + Text('Agregar parada', + style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold, color: AppTheme.textPrimary)), + Text('Selecciona un cliente o registra uno nuevo', + style: TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + ], + ), + ], + ), + const SizedBox(height: 14), + // Tabs + Container( + decoration: BoxDecoration( + color: AppTheme.bgColor, + borderRadius: BorderRadius.circular(10), + ), + child: TabBar( + controller: _tab, + indicator: BoxDecoration( + color: AppTheme.primaryColor, + borderRadius: BorderRadius.circular(8), + ), + labelColor: Colors.white, + unselectedLabelColor: AppTheme.textSecondary, + labelStyle: const TextStyle(fontWeight: FontWeight.w600, fontSize: 13), + tabs: const [ + Tab(text: 'Cliente registrado'), + Tab(text: 'Cliente nuevo'), + ], + ), + ), + ], + ), + ), + const SizedBox(height: 4), + Expanded( + child: TabBarView( + controller: _tab, + children: [ + // ── TAB 1: cliente registrado ── + _buildRegistradosTab(disponibles, scrollCtrl, hayMas), + // ── TAB 2: cliente nuevo ── + _buildNuevoTab(scrollCtrl), + ], + ), + ), + ], + ), + ); + } + + Widget _buildRegistradosTab(List disponibles, ScrollController scrollCtrl, bool hayMas) { + return Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 6), + child: TextField( + controller: _searchCtrl, + onChanged: (v) => setState(() => _query = v), + decoration: InputDecoration( + hintText: 'Buscar cliente...', + prefixIcon: const Icon(Icons.search, size: 20), + suffixIcon: _query.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear, size: 18), + onPressed: () { + _searchCtrl.clear(); + setState(() => _query = ''); + }, + ) + : null, + isDense: true, + ), + ), + ), + if (disponibles.isEmpty) + Expanded( + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.store_outlined, size: 48, color: Colors.grey.shade300), + const SizedBox(height: 10), + const Text('No hay clientes disponibles', + style: TextStyle(color: AppTheme.textSecondary)), + const SizedBox(height: 4), + const Text('Todos ya están en la ruta o\ncambia el filtro de búsqueda', + style: TextStyle(fontSize: 12, color: AppTheme.textSecondary), + textAlign: TextAlign.center), + ], + ), + ), + ) + else + Expanded( + child: ListView.builder( + controller: scrollCtrl, + padding: const EdgeInsets.fromLTRB(16, 0, 16, 12), + itemCount: disponibles.length + (hayMas ? 1 : 0), + itemBuilder: (_, i) { + if (i == disponibles.length) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Text( + 'Hay más clientes — refina la búsqueda para verlos', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12, color: Colors.grey.shade500), + ), + ); + } + final c = disponibles[i]; + final selected = _clienteElegido?.id == c.id; + return GestureDetector( + onTap: () => setState(() => _clienteElegido = c), + child: AnimatedContainer( + duration: const Duration(milliseconds: 150), + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + decoration: BoxDecoration( + color: selected ? AppTheme.primaryColor.withOpacity(0.07) : Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: selected ? AppTheme.primaryColor : const Color(0xFFE2E8F0), + width: selected ? 1.5 : 1, + ), + ), + child: Row( + children: [ + CircleAvatar( + radius: 20, + backgroundColor: selected + ? AppTheme.primaryColor.withOpacity(0.15) + : const Color(0xFFF1F5F9), + child: Icon(Icons.store, size: 20, + color: selected ? AppTheme.primaryColor : AppTheme.textSecondary), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(c.nombre, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: selected ? AppTheme.primaryColor : AppTheme.textPrimary, + )), + const SizedBox(height: 2), + Text(c.categoria, + style: TextStyle( + fontSize: 11, + color: selected ? AppTheme.primaryColor.withOpacity(0.7) : AppTheme.textSecondary, + )), + Text(c.direccion, + style: const TextStyle(fontSize: 11, color: AppTheme.textSecondary), + maxLines: 1, + overflow: TextOverflow.ellipsis), + ], + ), + ), + if (selected) + const Icon(Icons.check_circle, color: AppTheme.primaryColor, size: 22), + ], + ), + ), + ); + }, + ), + ), + // Footer + if (_clienteElegido != null) + _buildFooter(context), + ], + ); + } + + Widget _buildNuevoTab(ScrollController scrollCtrl) { + return SingleChildScrollView( + controller: scrollCtrl, + padding: const EdgeInsets.all(16), + child: Column( + children: [ + // Info banner + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: AppTheme.primaryColor.withOpacity(0.06), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: AppTheme.primaryColor.withOpacity(0.2)), + ), + child: Row( + children: [ + const Icon(Icons.info_outline, color: AppTheme.primaryColor, size: 18), + const SizedBox(width: 10), + Expanded( + child: Text( + 'El nuevo cliente quedará registrado en el sistema y se agregará como parada a tu ruta de hoy.', + style: TextStyle( + fontSize: 12, + color: AppTheme.primaryColor.withOpacity(0.85), + ), + ), + ), + ], + ), + ), + const SizedBox(height: 16), + SizedBox( + width: double.infinity, + height: 52, + child: ElevatedButton.icon( + icon: const Icon(Icons.person_add_alt_1_outlined, size: 22), + label: const Text('Abrir formulario de registro', + style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600)), + onPressed: () async { + Navigator.pop(context); // cierra el sheet + final nuevoCliente = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const ClienteFormScreen(), + ), + ); + // Si se creó con agregarARuta = true, el provider ya lo hizo. + // Si no, el cliente quedó registrado pero no en ruta. + if (nuevoCliente != null) { + // nada extra que hacer — el provider ya notificó + } + }, + ), + ), + ], + ), + ); + } + + Widget _buildFooter(BuildContext context) { + return Container( + padding: const EdgeInsets.fromLTRB(16, 10, 16, 20), + decoration: const BoxDecoration( + color: Colors.white, + border: Border(top: BorderSide(color: Color(0xFFE2E8F0))), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Cliente seleccionado: ${_clienteElegido!.nombre}', + style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary), + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: TextField( + controller: _horaCtrl, + keyboardType: TextInputType.datetime, + decoration: const InputDecoration( + labelText: 'Hora estimada', + prefixIcon: Icon(Icons.access_time, size: 18), + isDense: true, + ), + ), + ), + const SizedBox(width: 12), + Expanded( + flex: 2, + child: ElevatedButton.icon( + icon: const Icon(Icons.add_location_alt_outlined, size: 18), + label: const Text('Agregar a ruta'), + onPressed: () { + final hora = _horaCtrl.text.trim().isEmpty ? '—' : _horaCtrl.text.trim(); + widget.provider.agregarParadaARuta(_clienteElegido!, hora); + Navigator.pop(context); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('✓ ${_clienteElegido!.nombre} agregado a la ruta'), + backgroundColor: AppTheme.successColor, + behavior: SnackBarBehavior.floating, + ), + ); + }, + ), + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/screens/scanner/scanner_helper.dart b/lib/screens/scanner/scanner_helper.dart new file mode 100644 index 0000000..ca34bc9 --- /dev/null +++ b/lib/screens/scanner/scanner_helper.dart @@ -0,0 +1,64 @@ +import 'dart:io' show Platform; +import 'package:flutter/foundation.dart' show kIsWeb; +import 'package:flutter/material.dart'; +import 'scanner_screen.dart'; + +/// Abre el scanner de cámara en móvil/web, o un diálogo de entrada manual en Linux/Windows. +/// Retorna el valor escaneado/ingresado, o null si el usuario canceló. +Future abrirScanner(BuildContext context, {String titulo = 'Escanear código'}) { + if (!kIsWeb && (Platform.isLinux || Platform.isWindows)) { + return _mostrarInputManual(context, titulo: titulo); + } + return Navigator.push( + context, + MaterialPageRoute(builder: (_) => ScannerScreen(titulo: titulo)), + ); +} + +Future _mostrarInputManual(BuildContext context, {required String titulo}) { + final ctrl = TextEditingController(); + return showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Row( + children: [ + const Icon(Icons.qr_code, size: 22), + const SizedBox(width: 8), + Text(titulo, style: const TextStyle(fontSize: 16)), + ], + ), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text( + 'Escaneo de cámara no disponible en escritorio.\nIngresa el código manualmente:', + style: TextStyle(fontSize: 13, color: Colors.black54), + ), + const SizedBox(height: 14), + TextField( + controller: ctrl, + autofocus: true, + decoration: const InputDecoration( + labelText: 'Código / SKU', + prefixIcon: Icon(Icons.qr_code), + border: OutlineInputBorder(), + ), + onSubmitted: (v) { + if (v.trim().isNotEmpty) Navigator.pop(ctx, v.trim()); + }, + ), + ], + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Cancelar')), + ElevatedButton( + onPressed: () { + final v = ctrl.text.trim(); + if (v.isNotEmpty) Navigator.pop(ctx, v); + }, + child: const Text('Buscar'), + ), + ], + ), + ); +} diff --git a/lib/screens/scanner/scanner_screen.dart b/lib/screens/scanner/scanner_screen.dart new file mode 100644 index 0000000..72e61e1 --- /dev/null +++ b/lib/screens/scanner/scanner_screen.dart @@ -0,0 +1,136 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_scanner/mobile_scanner.dart'; +import '../../theme/app_theme.dart'; + +class ScannerScreen extends StatefulWidget { + final String titulo; + const ScannerScreen({Key? key, this.titulo = 'Escanear código'}) : super(key: key); + + @override + State createState() => _ScannerScreenState(); +} + +class _ScannerScreenState extends State { + final _controller = MobileScannerController(); + bool _scanned = false; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _onDetect(Barcode barcode, MobileScannerArguments? args) { + if (_scanned || barcode.rawValue == null || barcode.rawValue!.isEmpty) return; + _scanned = true; + Navigator.pop(context, barcode.rawValue); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.black, + foregroundColor: Colors.white, + elevation: 0, + title: Text(widget.titulo), + actions: [ + ValueListenableBuilder( + valueListenable: _controller.torchState, + builder: (_, state, __) => IconButton( + tooltip: state == TorchState.on ? 'Apagar linterna' : 'Encender linterna', + icon: Icon( + state == TorchState.on ? Icons.flash_on : Icons.flash_off, + color: state == TorchState.on ? Colors.yellow : Colors.white, + ), + onPressed: _controller.toggleTorch, + ), + ), + ValueListenableBuilder( + valueListenable: _controller.cameraFacingState, + builder: (_, facing, __) => IconButton( + tooltip: 'Cambiar cámara', + icon: const Icon(Icons.cameraswitch, color: Colors.white), + onPressed: _controller.switchCamera, + ), + ), + ], + ), + body: Stack( + children: [ + MobileScanner( + controller: _controller, + fit: BoxFit.cover, + onDetect: _onDetect, + ), + CustomPaint( + painter: _ScanOverlayPainter(), + child: const SizedBox.expand(), + ), + Positioned( + left: 0, + right: 0, + bottom: 56, + child: Column( + children: const [ + Icon(Icons.qr_code_scanner, color: Colors.white38, size: 28), + SizedBox(height: 10), + Text( + 'Apunta al código QR o código de barras', + textAlign: TextAlign.center, + style: TextStyle(color: Colors.white70, fontSize: 13), + ), + ], + ), + ), + ], + ), + ); + } +} + +class _ScanOverlayPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final frameSize = size.width * 0.72; + final left = (size.width - frameSize) / 2; + final top = (size.height - frameSize) / 2 - 40; + final frameRect = Rect.fromLTWH(left, top, frameSize, frameSize); + + // Semi-transparent overlay with hole + final overlayPaint = Paint()..color = Colors.black.withOpacity(0.55); + final outer = Path()..addRect(Rect.fromLTWH(0, 0, size.width, size.height)); + final inner = Path()..addRRect(RRect.fromRectAndRadius(frameRect, const Radius.circular(10))); + canvas.drawPath(Path.combine(PathOperation.difference, outer, inner), overlayPaint); + + // Corner brackets + final bracketPaint = Paint() + ..color = AppTheme.primaryColor + ..style = PaintingStyle.stroke + ..strokeWidth = 3.5 + ..strokeCap = StrokeCap.round; + + const cl = 22.0; // corner length + final l = frameRect.left; + final t = frameRect.top; + final r = frameRect.right; + final b = frameRect.bottom; + + // Top-left + canvas.drawLine(Offset(l, t + cl), Offset(l, t), bracketPaint); + canvas.drawLine(Offset(l, t), Offset(l + cl, t), bracketPaint); + // Top-right + canvas.drawLine(Offset(r - cl, t), Offset(r, t), bracketPaint); + canvas.drawLine(Offset(r, t), Offset(r, t + cl), bracketPaint); + // Bottom-left + canvas.drawLine(Offset(l, b - cl), Offset(l, b), bracketPaint); + canvas.drawLine(Offset(l, b), Offset(l + cl, b), bracketPaint); + // Bottom-right + canvas.drawLine(Offset(r - cl, b), Offset(r, b), bracketPaint); + canvas.drawLine(Offset(r, b), Offset(r, b - cl), bracketPaint); + } + + @override + bool shouldRepaint(_) => false; +} diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart new file mode 100644 index 0000000..25096a5 --- /dev/null +++ b/lib/services/notification_service.dart @@ -0,0 +1,130 @@ +import 'package:flutter/material.dart'; +import '../models/notificacion.dart'; +import '../widgets/notification_banner.dart'; + +class NotificationService extends ChangeNotifier { + final GlobalKey navigatorKey; + final List _notifications = []; + + NotificationService({required this.navigatorKey}); + + List get notifications => List.unmodifiable(_notifications); + int get unreadCount => _notifications.where((n) => !n.leida).length; + + void mostrar(Notificacion notif) { + _notifications.insert(0, notif); + notifyListeners(); + _showBanner(notif); + } + + void marcarTodasLeidas() { + for (final n in _notifications) { + n.leida = true; + } + notifyListeners(); + } + + void marcarLeida(String id) { + final idx = _notifications.indexWhere((n) => n.id == id); + if (idx >= 0) { + _notifications[idx].leida = true; + notifyListeners(); + } + } + + void eliminar(String id) { + _notifications.removeWhere((n) => n.id == id); + notifyListeners(); + } + + void _showBanner(Notificacion notif) { + final overlay = navigatorKey.currentState?.overlay; + if (overlay == null) return; + OverlayEntry? entry; + entry = OverlayEntry( + builder: (_) => NotificationBanner( + notificacion: notif, + onDismiss: () => entry?.remove(), + ), + ); + overlay.insert(entry); + } + + // ── Disparadores de conveniencia ───────────────────────────── + + void notifPedidoConfirmado(String id, String cliente) { + mostrar(Notificacion( + id: '${DateTime.now().millisecondsSinceEpoch}', + tipo: TipoNotificacion.pedidoConfirmado, + titulo: 'Pedido confirmado', + cuerpo: '$id firmado y confirmado — $cliente', + fecha: DateTime.now(), + )); + } + + void notifParadaVisitada(String cliente) { + mostrar(Notificacion( + id: '${DateTime.now().millisecondsSinceEpoch}', + tipo: TipoNotificacion.pedidoEntregado, + titulo: 'Visita completada', + cuerpo: 'Parada en $cliente marcada como visitada', + fecha: DateTime.now(), + )); + } + + void notifStockBajo(String producto, int stock) { + mostrar(Notificacion( + id: '${DateTime.now().millisecondsSinceEpoch}', + tipo: TipoNotificacion.stockBajo, + titulo: 'Stock bajo', + cuerpo: '$producto — solo $stock unidades disponibles', + fecha: DateTime.now(), + )); + } + + Future dispararDemo() async { + final base = DateTime.now().millisecondsSinceEpoch; + final demos = [ + Notificacion( + id: '${base}_1', + tipo: TipoNotificacion.paradaProxima, + titulo: 'Próxima parada en 15 min', + cuerpo: 'InfoSystems La Paz — Av. Mariscal Santa Cruz 1250', + fecha: DateTime.now(), + ), + Notificacion( + id: '${base}_2', + tipo: TipoNotificacion.stockBajo, + titulo: 'Stock bajo', + cuerpo: 'Router TP-Link AX3000 — solo 3 unidades disponibles', + fecha: DateTime.now(), + ), + Notificacion( + id: '${base}_3', + tipo: TipoNotificacion.pedidoConfirmado, + titulo: 'Pedido confirmado', + cuerpo: 'TTC-0047 firmado por TechZone Bolivia — Bs. 24,500.00', + fecha: DateTime.now(), + ), + Notificacion( + id: '${base}_4', + tipo: TipoNotificacion.metaVentas, + titulo: '¡Meta del día alcanzada!', + cuerpo: 'Superaste Bs. 15,000 en ventas. ¡Excelente trabajo, Roberto!', + fecha: DateTime.now(), + ), + Notificacion( + id: '${base}_5', + tipo: TipoNotificacion.recordatorio, + titulo: 'Recordatorio de visita', + cuerpo: 'Gobernación La Paz — contrato de renovación anual pendiente', + fecha: DateTime.now(), + ), + ]; + + for (final n in demos) { + await Future.delayed(const Duration(milliseconds: 950)); + mostrar(n); + } + } +} diff --git a/lib/theme/app_theme.dart b/lib/theme/app_theme.dart new file mode 100644 index 0000000..502cc43 --- /dev/null +++ b/lib/theme/app_theme.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; + +class AppTheme { + static const primaryColor = Color(0xFF1E40AF); + static const accentColor = Color(0xFFF97316); + static const successColor = Color(0xFF16A34A); + static const warningColor = Color(0xFFD97706); + static const dangerColor = Color(0xFFDC2626); + static const bgColor = Color(0xFFF1F5F9); + static const cardColor = Colors.white; + static const textPrimary = Color(0xFF1E293B); + static const textSecondary = Color(0xFF64748B); + + static ThemeData get light => ThemeData( + primaryColor: primaryColor, + colorScheme: ColorScheme.fromSwatch().copyWith( + primary: primaryColor, + secondary: accentColor, + ), + scaffoldBackgroundColor: bgColor, + appBarTheme: const AppBarTheme( + backgroundColor: primaryColor, + foregroundColor: Colors.white, + elevation: 0, + centerTitle: false, + ), + cardTheme: CardTheme( + color: cardColor, + elevation: 2, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), + ), + elevatedButtonTheme: ElevatedButtonThemeData( + style: ElevatedButton.styleFrom( + primary: primaryColor, + onPrimary: Colors.white, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14), + elevation: 2, + ), + ), + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: Colors.white, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Color(0xFFCBD5E1)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Color(0xFFCBD5E1)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: primaryColor, width: 2), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + ), + textTheme: const TextTheme( + headline5: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: textPrimary), + headline6: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: textPrimary), + subtitle1: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: textPrimary), + subtitle2: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: textSecondary), + bodyText1: TextStyle(fontSize: 14, color: textPrimary), + bodyText2: TextStyle(fontSize: 13, color: textSecondary), + caption: TextStyle(fontSize: 12, color: textSecondary), + ), + bottomNavigationBarTheme: const BottomNavigationBarThemeData( + backgroundColor: Colors.white, + selectedItemColor: primaryColor, + unselectedItemColor: Color(0xFF94A3B8), + selectedLabelStyle: TextStyle(fontWeight: FontWeight.w600, fontSize: 11), + unselectedLabelStyle: TextStyle(fontSize: 11), + showUnselectedLabels: true, + type: BottomNavigationBarType.fixed, + elevation: 8, + ), + chipTheme: ChipThemeData( + backgroundColor: const Color(0xFFE2E8F0), + selectedColor: primaryColor, + labelStyle: const TextStyle(fontSize: 12), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + ), + ); + + static Color estadoColor(String estado) { + switch (estado.toLowerCase()) { + case 'confirmado': return successColor; + case 'entregado': return const Color(0xFF0891B2); + case 'cancelado': return dangerColor; + default: return warningColor; + } + } +} diff --git a/lib/widgets/notification_banner.dart b/lib/widgets/notification_banner.dart new file mode 100644 index 0000000..8cb064b --- /dev/null +++ b/lib/widgets/notification_banner.dart @@ -0,0 +1,155 @@ +import 'package:flutter/material.dart'; +import '../models/notificacion.dart'; + +class NotificationBanner extends StatefulWidget { + final Notificacion notificacion; + final VoidCallback onDismiss; + + const NotificationBanner({ + Key? key, + required this.notificacion, + required this.onDismiss, + }) : super(key: key); + + @override + State createState() => _NotificationBannerState(); +} + +class _NotificationBannerState extends State + with SingleTickerProviderStateMixin { + late AnimationController _ctrl; + late Animation _slide; + late Animation _fade; + bool _dismissing = false; + + @override + void initState() { + super.initState(); + _ctrl = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 320), + ); + _slide = Tween( + begin: const Offset(0, -1.2), + end: Offset.zero, + ).animate(CurvedAnimation(parent: _ctrl, curve: Curves.easeOutBack)); + _fade = CurvedAnimation(parent: _ctrl, curve: Curves.easeOut); + + _ctrl.forward(); + Future.delayed(const Duration(milliseconds: 3800), _startDismiss); + } + + @override + void dispose() { + _ctrl.dispose(); + super.dispose(); + } + + Future _startDismiss() async { + if (_dismissing || !mounted) return; + _dismissing = true; + _ctrl.reverse(); + await Future.delayed(const Duration(milliseconds: 320)); + widget.onDismiss(); + } + + @override + Widget build(BuildContext context) { + final notif = widget.notificacion; + final color = notif.tipo.color; + + return Positioned( + top: MediaQuery.of(context).padding.top + 10, + left: 14, + right: 14, + child: SlideTransition( + position: _slide, + child: FadeTransition( + opacity: _fade, + child: Material( + elevation: 8, + borderRadius: BorderRadius.circular(14), + shadowColor: color.withOpacity(0.3), + child: GestureDetector( + onTap: _startDismiss, + child: Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border( + left: BorderSide(color: color, width: 4), + ), + ), + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 12, 8, 12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: color.withOpacity(0.12), + shape: BoxShape.circle, + ), + child: Icon(notif.tipo.icono, color: color, size: 18), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Expanded( + child: Text( + notif.titulo, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.bold, + color: Color(0xFF0F172A), + ), + ), + ), + const SizedBox(width: 4), + Text( + 'Ahora', + style: TextStyle( + fontSize: 11, + color: Colors.grey.shade500, + ), + ), + ], + ), + const SizedBox(height: 3), + Text( + notif.cuerpo, + style: const TextStyle( + fontSize: 12, + color: Color(0xFF475569), + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + GestureDetector( + onTap: _startDismiss, + child: Padding( + padding: const EdgeInsets.only(left: 4), + child: Icon(Icons.close, size: 16, color: Colors.grey.shade400), + ), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/route_map_painter.dart b/lib/widgets/route_map_painter.dart new file mode 100644 index 0000000..727c988 --- /dev/null +++ b/lib/widgets/route_map_painter.dart @@ -0,0 +1,224 @@ +import 'package:flutter/material.dart'; +import '../models/parada_ruta.dart'; +import '../theme/app_theme.dart'; + +class RouteMapPainter extends CustomPainter { + final List paradas; + + RouteMapPainter(this.paradas); + + @override + void paint(Canvas canvas, Size size) { + _drawMapBackground(canvas, size); + _drawGrid(canvas, size); + _drawRoute(canvas, size); + _drawMarkers(canvas, size); + } + + void _drawMapBackground(Canvas canvas, Size size) { + final bgPaint = Paint()..color = const Color(0xFFEEF2FF); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), bgPaint); + + // blocks + final blockPaint = Paint()..color = const Color(0xFFDDD6FE).withOpacity(0.4); + final blocks = [ + Rect.fromLTWH(size.width * 0.05, size.height * 0.08, size.width * 0.25, size.height * 0.15), + Rect.fromLTWH(size.width * 0.40, size.height * 0.05, size.width * 0.20, size.height * 0.18), + Rect.fromLTWH(size.width * 0.70, size.height * 0.10, size.width * 0.22, size.height * 0.12), + Rect.fromLTWH(size.width * 0.10, size.height * 0.35, size.width * 0.18, size.height * 0.20), + Rect.fromLTWH(size.width * 0.35, size.height * 0.30, size.width * 0.28, size.height * 0.22), + Rect.fromLTWH(size.width * 0.70, size.height * 0.30, size.width * 0.22, size.height * 0.25), + Rect.fromLTWH(size.width * 0.05, size.height * 0.62, size.width * 0.30, size.height * 0.18), + Rect.fromLTWH(size.width * 0.42, size.height * 0.60, size.width * 0.22, size.height * 0.20), + Rect.fromLTWH(size.width * 0.72, size.height * 0.62, size.width * 0.20, size.height * 0.18), + ]; + for (final r in blocks) { + canvas.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(4)), + blockPaint, + ); + } + + // roads + final roadPaint = Paint() + ..color = Colors.white + ..strokeWidth = 8 + ..strokeCap = StrokeCap.round; + + final roads = [ + [Offset(0, size.height * 0.28), Offset(size.width, size.height * 0.28)], + [Offset(0, size.height * 0.57), Offset(size.width, size.height * 0.57)], + [Offset(size.width * 0.32, 0), Offset(size.width * 0.32, size.height)], + [Offset(size.width * 0.65, 0), Offset(size.width * 0.65, size.height)], + ]; + for (final road in roads) { + canvas.drawLine(road[0], road[1], roadPaint); + } + } + + void _drawGrid(Canvas canvas, Size size) { + final gridPaint = Paint() + ..color = Colors.white.withOpacity(0.6) + ..strokeWidth = 1; + for (double x = 0; x < size.width; x += size.width / 8) { + canvas.drawLine(Offset(x, 0), Offset(x, size.height), gridPaint); + } + for (double y = 0; y < size.height; y += size.height / 6) { + canvas.drawLine(Offset(0, y), Offset(size.width, y), gridPaint); + } + } + + List _getPositions(Size size) { + // Fixed visual positions for the 6 stops + return [ + Offset(size.width * 0.18, size.height * 0.20), + Offset(size.width * 0.50, size.height * 0.15), + Offset(size.width * 0.80, size.height * 0.22), + Offset(size.width * 0.75, size.height * 0.50), + Offset(size.width * 0.45, size.height * 0.72), + Offset(size.width * 0.15, size.height * 0.68), + ]; + } + + void _drawRoute(Canvas canvas, Size size) { + if (paradas.isEmpty) return; + final positions = _getPositions(size); + final count = paradas.length < positions.length ? paradas.length : positions.length; + + // dashed line for future stops + final donePaint = Paint() + ..color = AppTheme.primaryColor.withOpacity(0.7) + ..strokeWidth = 2.5 + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke; + + final pendingPaint = Paint() + ..color = AppTheme.primaryColor.withOpacity(0.35) + ..strokeWidth = 2 + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke; + + for (int i = 0; i < count - 1; i++) { + final isVisited = paradas[i].estado == EstadoParada.visitado && + paradas[i + 1].estado == EstadoParada.visitado; + canvas.drawLine(positions[i], positions[i + 1], + isVisited ? donePaint : pendingPaint); + } + } + + void _drawMarkers(Canvas canvas, Size size) { + if (paradas.isEmpty) return; + final positions = _getPositions(size); + final count = paradas.length < positions.length ? paradas.length : positions.length; + + for (int i = 0; i < count; i++) { + final parada = paradas[i]; + final pos = positions[i]; + final isVisited = parada.estado == EstadoParada.visitado; + final isCurrent = parada.estado == EstadoParada.pendiente && + (i == 0 || paradas[i - 1].estado == EstadoParada.visitado); + + final color = isVisited + ? AppTheme.successColor + : isCurrent + ? AppTheme.accentColor + : AppTheme.primaryColor.withOpacity(0.5); + + // shadow + final shadowPaint = Paint() + ..color = Colors.black.withOpacity(0.15) + ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 3); + canvas.drawCircle(pos + const Offset(0, 2), isCurrent ? 16 : 13, shadowPaint); + + // outer ring for current + if (isCurrent) { + final ringPaint = Paint() + ..color = AppTheme.accentColor.withOpacity(0.25) + ..style = PaintingStyle.fill; + canvas.drawCircle(pos, 22, ringPaint); + } + + // marker body + final markerPaint = Paint()..color = color; + canvas.drawCircle(pos, isCurrent ? 16 : 13, markerPaint); + + // white inner + final innerPaint = Paint()..color = Colors.white; + canvas.drawCircle(pos, isCurrent ? 9 : 7, innerPaint); + + // number + final textPainter = TextPainter( + text: TextSpan( + text: '${i + 1}', + style: TextStyle( + color: color, + fontSize: isCurrent ? 10 : 8, + fontWeight: FontWeight.bold, + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + textPainter.paint( + canvas, + pos - Offset(textPainter.width / 2, textPainter.height / 2), + ); + + // label chip + _drawLabel(canvas, pos, parada.cliente.nombre.split(' ').first, color, isCurrent); + } + + // current position indicator (GPS dot) + if (count > 0) { + final currentIndex = paradas.indexWhere((p) => p.estado == EstadoParada.pendiente); + if (currentIndex >= 0 && currentIndex < positions.length) { + final gpsPos = positions[currentIndex] + const Offset(-24, -24); + final gpsPaint = Paint()..color = Colors.blue; + canvas.drawCircle(gpsPos, 7, gpsPaint); + final gpsBorderPaint = Paint() + ..color = Colors.white + ..style = PaintingStyle.stroke + ..strokeWidth = 2; + canvas.drawCircle(gpsPos, 7, gpsBorderPaint); + final gpsPulsePaint = Paint() + ..color = Colors.blue.withOpacity(0.25); + canvas.drawCircle(gpsPos, 12, gpsPulsePaint); + } + } + } + + void _drawLabel(Canvas canvas, Offset pos, String text, Color color, bool isCurrent) { + final tp = TextPainter( + text: TextSpan( + text: text, + style: const TextStyle( + color: AppTheme.textPrimary, + fontSize: 9, + fontWeight: FontWeight.w600, + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + + const padding = 4.0; + final chipW = tp.width + padding * 2; + const chipH = 16.0; + final chipOffset = Offset(pos.dx - chipW / 2, pos.dy + (isCurrent ? 20 : 17)); + + final chipBg = Paint()..color = Colors.white.withOpacity(0.9); + final chipBorder = Paint() + ..color = color.withOpacity(0.5) + ..style = PaintingStyle.stroke + ..strokeWidth = 1; + + final chipRect = RRect.fromRectAndRadius( + Rect.fromLTWH(chipOffset.dx, chipOffset.dy, chipW, chipH), + const Radius.circular(4), + ); + canvas.drawRRect(chipRect, chipBg); + canvas.drawRRect(chipRect, chipBorder); + tp.paint(canvas, chipOffset + const Offset(padding, 3)); + } + + @override + bool shouldRepaint(RouteMapPainter oldDelegate) => true; +} diff --git a/lib/widgets/signature_pad.dart b/lib/widgets/signature_pad.dart new file mode 100644 index 0000000..e6851a1 --- /dev/null +++ b/lib/widgets/signature_pad.dart @@ -0,0 +1,102 @@ +import 'package:flutter/material.dart'; +import '../theme/app_theme.dart'; + +class SignaturePad extends StatefulWidget { + final void Function(List> strokes) onChanged; + + const SignaturePad({Key? key, required this.onChanged}) : super(key: key); + + @override + State createState() => SignaturePadState(); +} + +class SignaturePadState extends State { + final List> _strokes = []; + List _current = []; + + bool get isEmpty => _strokes.isEmpty; + + void clear() { + setState(() { + _strokes.clear(); + _current = []; + }); + widget.onChanged([]); + } + + @override + Widget build(BuildContext context) { + return GestureDetector( + onPanStart: (details) { + setState(() { + _current = [details.localPosition]; + }); + }, + onPanUpdate: (details) { + setState(() { + _current = [..._current, details.localPosition]; + }); + }, + onPanEnd: (_) { + if (_current.isNotEmpty) { + setState(() { + _strokes.add(List.from(_current)); + _current = []; + }); + widget.onChanged(List.from(_strokes)); + } + }, + child: CustomPaint( + painter: _SignaturePainter(strokes: _strokes, current: _current), + child: Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFCBD5E1), width: 1.5), + ), + ), + ), + ); + } +} + +class _SignaturePainter extends CustomPainter { + final List> strokes; + final List current; + + _SignaturePainter({required this.strokes, required this.current}); + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = AppTheme.primaryColor + ..strokeWidth = 2.5 + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..style = PaintingStyle.stroke; + + for (final stroke in strokes) { + _drawStroke(canvas, stroke, paint); + } + if (current.isNotEmpty) { + _drawStroke(canvas, current, paint); + } + } + + void _drawStroke(Canvas canvas, List points, Paint paint) { + if (points.length < 2) return; + final path = Path()..moveTo(points[0].dx, points[0].dy); + for (int i = 1; i < points.length - 1; i++) { + final mid = Offset( + (points[i].dx + points[i + 1].dx) / 2, + (points[i].dy + points[i + 1].dy) / 2, + ); + path.quadraticBezierTo(points[i].dx, points[i].dy, mid.dx, mid.dy); + } + path.lineTo(points.last.dx, points.last.dy); + canvas.drawPath(path, paint); + } + + @override + bool shouldRepaint(_SignaturePainter old) => true; +} diff --git a/lib/widgets/stat_card.dart b/lib/widgets/stat_card.dart new file mode 100644 index 0000000..778b498 --- /dev/null +++ b/lib/widgets/stat_card.dart @@ -0,0 +1,80 @@ +import 'package:flutter/material.dart'; +import '../theme/app_theme.dart'; + +class StatCard extends StatelessWidget { + final String titulo; + final String valor; + final String subtitulo; + final IconData icono; + final Color color; + + const StatCard({ + Key? key, + required this.titulo, + required this.valor, + required this.subtitulo, + required this.icono, + required this.color, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: AppTheme.cardColor, + borderRadius: BorderRadius.circular(14), + boxShadow: [ + BoxShadow( + color: color.withOpacity(0.15), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Text( + titulo, + style: const TextStyle( + fontSize: 12, + color: AppTheme.textSecondary, + fontWeight: FontWeight.w500, + ), + ), + ), + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: color.withOpacity(0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Icon(icono, color: color, size: 18), + ), + ], + ), + const SizedBox(height: 10), + Text( + valor, + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.bold, + color: color, + ), + ), + const SizedBox(height: 4), + Text( + subtitulo, + style: const TextStyle(fontSize: 11, color: AppTheme.textSecondary), + ), + ], + ), + ); + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..2546e80 --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,138 @@ +# 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 "pedidos_app") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.pedidosapp.pedidos_app") + +# 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) + +# 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/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/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/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e71a16d --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/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/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..2e1de87 --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +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/linux/main.cc b/linux/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/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/linux/my_application.cc b/linux/my_application.cc new file mode 100644 index 0000000..54703c9 --- /dev/null +++ b/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, "Agente Ventas SIGMAC"); + 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, "Agente Ventas SIGMAC"); + } + + 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/linux/my_application.h b/linux/my_application.h new file mode 100644 index 0000000..72271d5 --- /dev/null +++ b/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/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..602bc83 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import mobile_scanner +import sqflite + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) + SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..2503538 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,572 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 51; + 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 */ + 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 */ + 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 */ + 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 /* pedidos_app.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "pedidos_app.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 */ + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 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 */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* pedidos_app.app */, + ); + 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 */ + 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 /* pedidos_app.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1300; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 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 */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 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; + 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 */ + 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 */ + 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 */ + 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.11; + 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.11; + 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.11; + 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 */ + 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/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..7645a8c --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..d53ef64 --- /dev/null +++ b/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/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/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/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..3c4935a Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..ed4cc16 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..483be61 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bcbf36d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..9c0a652 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..e71a726 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..8a31fe2 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..223c154 --- /dev/null +++ b/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 = pedidos_app + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.pedidosapp.pedidosApp + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.pedidosapp. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/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/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/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/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/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/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..2722837 --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController.init() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..17b72cd --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,322 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + archive: + dependency: transitive + description: + name: archive + url: "https://pub.dartlang.org" + source: hosted + version: "3.4.2" + args: + dependency: transitive + description: + name: args + url: "https://pub.dartlang.org" + source: hosted + version: "2.3.1" + async: + dependency: transitive + description: + name: async + url: "https://pub.dartlang.org" + source: hosted + version: "2.8.2" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + characters: + dependency: transitive + description: + name: characters + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + charcode: + dependency: transitive + description: + name: charcode + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.1" + clock: + dependency: transitive + description: + name: clock + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + collection: + dependency: transitive + description: + name: collection + url: "https://pub.dartlang.org" + source: hosted + version: "1.15.0" + convert: + dependency: transitive + description: + name: convert + url: "https://pub.dartlang.org" + source: hosted + version: "3.1.0" + crypto: + dependency: transitive + description: + name: crypto + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.2" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.5" + fake_async: + dependency: transitive + description: + name: fake_async + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + ffi: + dependency: transitive + description: + name: ffi + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_launcher_icons: + dependency: "direct dev" + description: + name: flutter_launcher_icons + url: "https://pub.dartlang.org" + source: hosted + version: "0.9.3" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.4" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + image: + dependency: transitive + description: + name: image + url: "https://pub.dartlang.org" + source: hosted + version: "3.1.3" + intl: + dependency: "direct main" + description: + name: intl + url: "https://pub.dartlang.org" + source: hosted + version: "0.17.0" + js: + dependency: transitive + description: + name: js + url: "https://pub.dartlang.org" + source: hosted + version: "0.6.5" + lints: + dependency: transitive + description: + name: lints + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" + matcher: + dependency: transitive + description: + name: matcher + url: "https://pub.dartlang.org" + source: hosted + version: "0.12.11" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.3" + meta: + dependency: transitive + description: + name: meta + url: "https://pub.dartlang.org" + source: hosted + version: "1.7.0" + mobile_scanner: + dependency: "direct main" + description: + name: mobile_scanner + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.0" + nested: + dependency: transitive + description: + name: nested + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.0" + path: + dependency: "direct main" + description: + name: path + url: "https://pub.dartlang.org" + source: hosted + version: "1.8.1" + petitparser: + dependency: transitive + description: + name: petitparser + url: "https://pub.dartlang.org" + source: hosted + version: "4.4.0" + pointycastle: + dependency: transitive + description: + name: pointycastle + url: "https://pub.dartlang.org" + source: hosted + version: "3.7.3" + provider: + dependency: "direct main" + description: + name: provider + url: "https://pub.dartlang.org" + source: hosted + version: "6.1.5+1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_span: + dependency: transitive + description: + name: source_span + url: "https://pub.dartlang.org" + source: hosted + version: "1.8.1" + sqflite: + dependency: "direct main" + description: + name: sqflite + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.2+1" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + url: "https://pub.dartlang.org" + source: hosted + version: "2.4.0" + sqflite_common_ffi: + dependency: "direct main" + description: + name: sqflite_common_ffi + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.1+1" + sqlite3: + dependency: transitive + description: + name: sqlite3 + url: "https://pub.dartlang.org" + source: hosted + version: "1.7.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + url: "https://pub.dartlang.org" + source: hosted + version: "1.10.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + string_scanner: + dependency: transitive + description: + name: string_scanner + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + synchronized: + dependency: transitive + description: + name: synchronized + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.0+3" + term_glyph: + dependency: transitive + description: + name: term_glyph + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + test_api: + dependency: transitive + description: + name: test_api + url: "https://pub.dartlang.org" + source: hosted + version: "0.4.9" + typed_data: + dependency: transitive + description: + name: typed_data + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.0" + vector_math: + dependency: transitive + description: + name: vector_math + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.1" + xml: + dependency: transitive + description: + name: xml + url: "https://pub.dartlang.org" + source: hosted + version: "5.3.1" + yaml: + dependency: transitive + description: + name: yaml + url: "https://pub.dartlang.org" + source: hosted + version: "3.1.1" +sdks: + dart: ">=2.17.0-69.2.beta <3.0.0" + flutter: ">=1.16.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..042613a --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,34 @@ +name: agente_ventas +description: App de pedidos y rutas de ventas para vendedores de campo — SIGMAC. +publish_to: 'none' +version: 1.0.0+1 + +environment: + sdk: ">=2.17.0-69.2.beta <3.0.0" + +dependencies: + flutter: + sdk: flutter + cupertino_icons: ^1.0.2 + provider: ^6.0.2 + intl: ^0.17.0 + sqflite: ^2.0.2+1 + sqflite_common_ffi: ^2.1.0 + path: ^1.8.1 + mobile_scanner: ^0.2.0 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^1.0.0 + flutter_launcher_icons: ^0.9.3 + +flutter_icons: + android: true + ios: true + image_path: "assets/icon/icon.png" + +flutter: + uses-material-design: true + assets: + - assets/icon/ diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..0d3c782 --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,7 @@ +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('Placeholder test', (WidgetTester tester) async { + expect(true, isTrue); + }); +} diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..d48d916 --- /dev/null +++ b/web/index.html @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + Agente Ventas SIGMAC + + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..d5ad7b7 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "Agente Ventas SIGMAC", + "short_name": "Agente Ventas", + "start_url": ".", + "display": "standalone", + "background_color": "#1E3A8A", + "theme_color": "#1E40AF", + "description": "Gestión de rutas y pedidos de campo — SIGMAC.", + "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/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/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/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..08dc9dc --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,101 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(pedidos_app 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 "pedidos_app") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# 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() + +# 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/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..930d207 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,104 @@ +# 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") + +# === 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" + windows-x64 $ + 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/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/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/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..b93c4c3 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +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/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..b9e550f --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,32 @@ +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}) + +# 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_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/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..e9ad9a3 --- /dev/null +++ b/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 +// + +#ifdef FLUTTER_BUILD_NUMBER +#define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER +#else +#define VERSION_AS_NUMBER 1,0,0 +#endif + +#ifdef FLUTTER_BUILD_NAME +#define VERSION_AS_STRING #FLUTTER_BUILD_NAME +#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.pedidosapp" "\0" + VALUE "FileDescription", "pedidos_app" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "pedidos_app" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.pedidosapp. All rights reserved." "\0" + VALUE "OriginalFilename", "pedidos_app.exe" "\0" + VALUE "ProductName", "pedidos_app" "\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/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..b43b909 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,61 @@ +#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()); + 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/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/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/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..c1c95af --- /dev/null +++ b/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.CreateAndShow(L"Agente Ventas SIGMAC", 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/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/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/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..c977c4a --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..d19bdbb --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#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); + if (target_length == 0) { + return std::string(); + } + std::string utf8_string; + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/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/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..c10f08d --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,245 @@ +#include "win32_window.h" + +#include + +#include "resource.h" + +namespace { + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +// 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 registar 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::CreateAndShow(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 | WS_VISIBLE, + 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; + } + + return OnCreate(); +} + +// 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; + } + + 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. +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..17ba431 --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,98 @@ +#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 and shows a win32 window with |title| and position and size 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 to will treat the width height passed in to this function + // as logical pixels and scale to appropriate for the default monitor. Returns + // true if the window was created successfully. + bool CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size); + + // 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 + // responsponds 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; + + 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_