diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3820a95 --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..768732a --- /dev/null +++ b/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "559ffa3f75e7402d65a8def9c28389a9b2e6fe42" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: android + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: ios + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: linux + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: macos + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: web + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: windows + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..74a5682 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,24 @@ +include: package:flutter_lints/flutter.yaml + +analyzer: + exclude: + - "**/*.g.dart" + - "**/*.freezed.dart" + language: + strict-casts: true + strict-raw-types: true + errors: + invalid_annotation_target: ignore + +linter: + rules: + - always_declare_return_types + - avoid_print + - prefer_const_constructors + - prefer_const_declarations + - prefer_final_locals + - prefer_single_quotes + - require_trailing_commas + - sort_child_properties_last + - unawaited_futures + - use_super_parameters diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..b91bb34 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,45 @@ +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.example.nearle_pos" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.nearle_pos" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + 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.getByName("debug") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /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..aab3ce0 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/example/nearle_pos/MainActivity.kt b/android/app/src/main/kotlin/com/example/nearle_pos/MainActivity.kt new file mode 100644 index 0000000..a9f05de --- /dev/null +++ b/android/app/src/main/kotlin/com/example/nearle_pos/MainActivity.kt @@ -0,0 +1,5 @@ +package com.example.nearle_pos + +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..06952be --- /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..cb1ef88 --- /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..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..e96108c --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2d428bf --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..c21f0c5 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "9.0.1" apply false + id("org.jetbrains.kotlin.android") version "2.3.20" apply false +} + +include(":app") diff --git a/assets/sounds/beep_error.wav b/assets/sounds/beep_error.wav new file mode 100644 index 0000000..715ab6f Binary files /dev/null and b/assets/sounds/beep_error.wav differ diff --git a/assets/sounds/beep_success.wav b/assets/sounds/beep_success.wav new file mode 100644 index 0000000..25edfa0 Binary files /dev/null and b/assets/sounds/beep_success.wav differ diff --git a/assets/sounds/charge_complete.wav b/assets/sounds/charge_complete.wav new file mode 100644 index 0000000..641c1e3 Binary files /dev/null and b/assets/sounds/charge_complete.wav differ 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..391a902 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.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..10f232d --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,644 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 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 PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 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 = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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 */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + 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; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + 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 = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.nearlePos; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.nearlePos.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.nearlePos.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.nearlePos.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + 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; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + 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 = 13.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; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + 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; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + 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 = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.nearlePos; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.nearlePos; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency 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..c3fedb2 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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..c30b367 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} 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..7353c41 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..797d452 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..6ed2d93 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..4cd7b00 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..fe73094 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..321773c 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..797d452 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..502f463 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..0ec3034 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..0ec3034 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..e9f5fea 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..84ac32a 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..8953cba 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..0467bf1 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..c65aa8f --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Nearle Pos + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + nearle_pos + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + 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/ios/Runner/SceneDelegate.swift b/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b9ce8ea --- /dev/null +++ b/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/app/app.dart b/lib/app/app.dart new file mode 100644 index 0000000..932201e --- /dev/null +++ b/lib/app/app.dart @@ -0,0 +1,27 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../core/constants/app_constants.dart'; +import '../core/router/app_router.dart'; +import '../core/theme/app_theme.dart'; + +class NearlePosApp extends ConsumerWidget { + const NearlePosApp({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + return MaterialApp.router( + title: AppConstants.appName, + debugShowCheckedModeBanner: false, + theme: AppTheme.light, + routerConfig: ref.watch(routerProvider), + builder: (context, child) { + // A POS runs on fixed hardware; ignore OS font scaling so the dense + // billing panel can never overflow. + return MediaQuery.withNoTextScaling( + child: child ?? const SizedBox.shrink(), + ); + }, + ); + } +} diff --git a/lib/app/providers.dart b/lib/app/providers.dart new file mode 100644 index 0000000..a51b93c --- /dev/null +++ b/lib/app/providers.dart @@ -0,0 +1,91 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../core/services/receipt_service.dart'; +import '../core/services/sound_service.dart'; +import '../data/datasources/local_store.dart'; +import '../data/repositories/customer_repository_impl.dart'; +import '../data/repositories/product_repository_impl.dart'; +import '../data/datasources/remote_catalogue_source.dart'; +import '../data/repositories/sync_repository_impl.dart'; +import '../data/repositories/transaction_repository_impl.dart'; +import '../domain/repositories/customer_repository.dart'; +import '../domain/repositories/product_repository.dart'; +import '../domain/repositories/sync_repository.dart'; +import '../domain/repositories/transaction_repository.dart'; +import '../domain/usecases/checkout_sale.dart'; + +/// Root data source. Overridden in tests with an in-memory double. +final localStoreProvider = Provider((ref) => LocalStore.instance); + +// ---------------------------------------------------------- Repositories +final productRepositoryProvider = Provider( + (ref) => ProductRepositoryImpl(ref.watch(localStoreProvider)), +); + +final customerRepositoryProvider = Provider( + (ref) => CustomerRepositoryImpl(ref.watch(localStoreProvider)), +); + +final transactionRepositoryProvider = Provider( + (ref) => TransactionRepositoryImpl(ref.watch(localStoreProvider)), +); + +/// Simulated back-office endpoints. Held as singletons so the offline toggle +/// in Settings affects every call. +final remoteCatalogueProvider = + Provider((ref) => RemoteCatalogueSource()); + +final remoteReportSinkProvider = + Provider((ref) => RemoteReportSink()); + +final syncRepositoryProvider = Provider( + (ref) => SyncRepositoryImpl( + ref.watch(localStoreProvider), + ref.watch(remoteCatalogueProvider), + ref.watch(remoteReportSinkProvider), + ), +); + +// ------------------------------------------------------------- Use cases +final checkoutSaleProvider = Provider( + (ref) => CheckoutSale( + productRepository: ref.watch(productRepositoryProvider), + customerRepository: ref.watch(customerRepositoryProvider), + transactionRepository: ref.watch(transactionRepositoryProvider), + ), +); + +// -------------------------------------------------------------- Services +final soundServiceProvider = + Provider((ref) => SoundService.instance); + +final receiptServiceProvider = + Provider((ref) => ReceiptService.instance); + +// --------------------------------------------------------------- Session +class CashierSession { + const CashierSession({ + required this.name, + required this.role, + required this.terminalId, + }); + + final String name; + final String role; + final String terminalId; +} + +final cashierSessionProvider = StateProvider( + (ref) => const CashierSession( + name: 'Suriya', + role: 'ADMIN', + terminalId: 'TERM-01', + ), +); + +/// Ticks once a minute to drive the header clock without rebuilding on every +/// frame. +final clockProvider = StreamProvider((ref) async* { + yield DateTime.now(); + yield* Stream.periodic(const Duration(seconds: 20), (_) => DateTime.now()); +}); diff --git a/lib/core/constants/app_constants.dart b/lib/core/constants/app_constants.dart new file mode 100644 index 0000000..4fbe5ff --- /dev/null +++ b/lib/core/constants/app_constants.dart @@ -0,0 +1,49 @@ +/// Application-wide configuration constants. +class AppConstants { + const AppConstants._(); + + static const String appName = 'Nearle POS'; + static const String storeName = 'Nearle Daily'; + static const String storeAddress = '12 Gandhipuram Main Rd, Coimbatore 641012'; + static const String storeGstin = '33ABCDE1234F1Z5'; + static const String storePhone = '+91 90000 12345'; + static const String currencySymbol = '\u20B9'; + static const String locale = 'en_IN'; + + /// Standard GST slab applied when a product does not declare its own. + static const double defaultGstRate = 0.18; + + /// One loyalty point is earned per this many rupees of net sale value. + static const double loyaltyRupeesPerPoint = 10; + + /// Rupee value of a single loyalty point when redeemed. + static const double loyaltyPointValue = 0.25; + + static const int mobileNumberLength = 10; + + /// Barcode scanners emit keystrokes fast; anything slower is human typing. + static const Duration barcodeScanTimeout = Duration(milliseconds: 120); + static const int minBarcodeLength = 6; + + /// Idle time after a completed sale before the terminal resets itself. + static const Duration postSaleResetDelay = Duration(seconds: 3); + + static const int lowStockThreshold = 10; + static const int maxParkedBills = 20; + static const int maxCartQuantityPerLine = 999; +} + +/// Hive box names. +class StorageKeys { + const StorageKeys._(); + + static const String products = 'box_products'; + static const String customers = 'box_customers'; + static const String transactions = 'box_transactions'; + static const String parkedBills = 'box_parked_bills'; + static const String settings = 'box_settings'; + + static const String cashierName = 'cashier_name'; + static const String cashierRole = 'cashier_role'; + static const String terminalId = 'terminal_id'; +} diff --git a/lib/core/constants/asset_paths.dart b/lib/core/constants/asset_paths.dart new file mode 100644 index 0000000..c833145 --- /dev/null +++ b/lib/core/constants/asset_paths.dart @@ -0,0 +1,13 @@ +/// Typed references to bundled assets. +/// +/// Only sounds are bundled: product imagery uses emoji glyphs and the welcome +/// artwork is painted in code, so there are no raster or SVG assets to ship. +class AssetPaths { + const AssetPaths._(); + + static const String _snd = 'assets/sounds'; + + static const String beepSuccess = '$_snd/beep_success.wav'; + static const String beepError = '$_snd/beep_error.wav'; + static const String chargeComplete = '$_snd/charge_complete.wav'; +} diff --git a/lib/core/router/app_router.dart b/lib/core/router/app_router.dart new file mode 100644 index 0000000..1e2685b --- /dev/null +++ b/lib/core/router/app_router.dart @@ -0,0 +1,140 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../domain/entities/transaction.dart'; +import '../../presentation/auth/providers/auth_controller.dart'; +import '../../presentation/auth/screens/login_screen.dart'; +import '../../presentation/customer/screens/customer_registration_screen.dart'; +import '../../presentation/customer/screens/existing_customer_screen.dart'; +import '../../presentation/payment/screens/payment_screen.dart'; +import '../../presentation/pos/screens/pos_dashboard_screen.dart'; +import '../../presentation/receipt/screens/receipt_screen.dart'; +import '../../presentation/welcome/screens/welcome_screen.dart'; + +class AppRoutes { + const AppRoutes._(); + + static const String login = '/login'; + static const String welcome = '/'; + static const String registerCustomer = '/customer/new'; + static const String existingCustomer = '/customer/find'; + static const String pos = '/pos'; + static const String payment = '/pos/payment'; + static const String receipt = '/pos/receipt'; +} + +/// Router with an authentication guard. +/// +/// Every route except [AppRoutes.login] requires a signed-in store, and an +/// already-signed-in terminal is bounced away from the login screen. +final routerProvider = Provider((ref) { + // GoRouter re-evaluates `redirect` whenever this notifier fires. + final authChanged = ValueNotifier( + ref.read(authControllerProvider).isAuthenticated, + ); + ref.listen( + authControllerProvider, + (_, next) => authChanged.value = next.isAuthenticated, + ); + ref.onDispose(authChanged.dispose); + + return GoRouter( + initialLocation: AppRoutes.login, + refreshListenable: authChanged, + debugLogDiagnostics: false, + redirect: (context, state) { + final signedIn = ref.read(authControllerProvider).isAuthenticated; + final atLogin = state.matchedLocation == AppRoutes.login; + + if (!signedIn) return atLogin ? null : AppRoutes.login; + if (atLogin) return AppRoutes.welcome; + return null; + }, + routes: [ + GoRoute( + path: AppRoutes.login, + name: 'login', + pageBuilder: (context, state) => _fade(state, const LoginScreen()), + ), + GoRoute( + path: AppRoutes.welcome, + name: 'welcome', + pageBuilder: (context, state) => _fade(state, const WelcomeScreen()), + ), + GoRoute( + path: AppRoutes.registerCustomer, + name: 'registerCustomer', + pageBuilder: (context, state) => _slide( + state, + CustomerRegistrationScreen( + prefillMobile: state.uri.queryParameters['mobile'], + ), + ), + ), + GoRoute( + path: AppRoutes.existingCustomer, + name: 'existingCustomer', + pageBuilder: (context, state) => + _slide(state, const ExistingCustomerScreen()), + ), + GoRoute( + path: AppRoutes.pos, + name: 'pos', + pageBuilder: (context, state) => + _fade(state, const PosDashboardScreen()), + routes: [ + GoRoute( + path: 'payment', + name: 'payment', + pageBuilder: (context, state) => + _slide(state, const PaymentScreen()), + ), + GoRoute( + path: 'receipt', + name: 'receipt', + pageBuilder: (context, state) => _fade( + state, + ReceiptScreen(transaction: state.extra! as SaleTransaction), + ), + ), + ], + ), + ], + errorBuilder: (context, state) => Scaffold( + body: Center(child: Text('Route not found: ${state.uri}')), + ), + ); +}); + +CustomTransitionPage _fade(GoRouterState state, Widget child) { + return CustomTransitionPage( + key: state.pageKey, + child: child, + transitionDuration: const Duration(milliseconds: 220), + transitionsBuilder: (_, animation, __, child) => + FadeTransition(opacity: animation, child: child), + ); +} + +CustomTransitionPage _slide(GoRouterState state, Widget child) { + return CustomTransitionPage( + key: state.pageKey, + child: child, + transitionDuration: const Duration(milliseconds: 260), + transitionsBuilder: (_, animation, __, child) { + final curved = + CurvedAnimation(parent: animation, curve: Curves.easeOutCubic); + return FadeTransition( + opacity: curved, + child: SlideTransition( + position: Tween( + begin: const Offset(0, 0.03), + end: Offset.zero, + ).animate(curved), + child: child, + ), + ); + }, + ); +} diff --git a/lib/core/services/barcode_service.dart b/lib/core/services/barcode_service.dart new file mode 100644 index 0000000..b1798d1 --- /dev/null +++ b/lib/core/services/barcode_service.dart @@ -0,0 +1,91 @@ +import 'dart:async'; + +import 'package:flutter/services.dart'; + +import '../constants/app_constants.dart'; + +/// Detects hardware barcode scanners that emulate a keyboard. +/// +/// Such scanners emit an entire code in a few milliseconds and terminate it +/// with Enter. We buffer raw key events and only treat the buffer as a scan +/// when the characters arrived faster than a human could type — that way the +/// cashier can still type into the same field by hand. +class BarcodeService { + BarcodeService({this.onScan, this.onManualKey}); + + final void Function(String code)? onScan; + final VoidCallback? onManualKey; + + final StringBuffer _buffer = StringBuffer(); + DateTime? _lastKeyAt; + Timer? _flushTimer; + + bool _attached = false; + + void attach() { + if (_attached) return; + HardwareKeyboard.instance.addHandler(_handleKey); + _attached = true; + } + + void detach() { + if (!_attached) return; + HardwareKeyboard.instance.removeHandler(_handleKey); + _flushTimer?.cancel(); + _attached = false; + } + + bool _handleKey(KeyEvent event) { + if (event is! KeyDownEvent) return false; + + final now = DateTime.now(); + final gap = _lastKeyAt == null + ? Duration.zero + : now.difference(_lastKeyAt!); + _lastKeyAt = now; + + // A long pause means a new entry started; discard whatever was buffered. + if (gap > AppConstants.barcodeScanTimeout) { + _buffer.clear(); + } + + if (event.logicalKey == LogicalKeyboardKey.enter || + event.logicalKey == LogicalKeyboardKey.numpadEnter) { + return _flush(); + } + + final char = event.character; + if (char == null || char.trim().isEmpty) return false; + if (!RegExp(r'^[0-9A-Za-z\-]$').hasMatch(char)) return false; + + _buffer.write(char); + _scheduleFlush(); + return false; + } + + /// Some scanners are not configured to send a terminating Enter, so we also + /// flush on a short idle window. + void _scheduleFlush() { + _flushTimer?.cancel(); + _flushTimer = Timer( + AppConstants.barcodeScanTimeout * 2, + () => _flush(), + ); + } + + bool _flush() { + _flushTimer?.cancel(); + final code = _buffer.toString().trim(); + _buffer.clear(); + + if (code.length >= AppConstants.minBarcodeLength) { + onScan?.call(code); + return true; + } + + if (code.isNotEmpty) onManualKey?.call(); + return false; + } + + void dispose() => detach(); +} diff --git a/lib/core/services/receipt_service.dart b/lib/core/services/receipt_service.dart new file mode 100644 index 0000000..05c27a4 --- /dev/null +++ b/lib/core/services/receipt_service.dart @@ -0,0 +1,335 @@ +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; +import 'package:pdf/pdf.dart'; +import 'package:pdf/widgets.dart' as pw; +import 'package:printing/printing.dart'; + +import '../../domain/entities/transaction.dart'; +import '../constants/app_constants.dart'; +import '../utils/formatters.dart'; + +/// Builds and prints an 80mm thermal GST invoice. +class ReceiptService { + ReceiptService._(); + + static final ReceiptService instance = ReceiptService._(); + + /// 80mm roll with a small safety margin. + static const double _rollWidth = 78 * PdfPageFormat.mm; + + Future build(SaleTransaction txn) async { + final doc = pw.Document(title: txn.invoiceNumber); + final font = await PdfGoogleFonts.interRegular(); + final bold = await PdfGoogleFonts.interSemiBold(); + + final cart = txn.cart; + + doc.addPage( + pw.Page( + pageFormat: PdfPageFormat( + _rollWidth, + double.infinity, + marginAll: 6 * PdfPageFormat.mm, + ), + theme: pw.ThemeData.withFont(base: font, bold: bold), + build: (context) => pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.stretch, + children: [ + _header(txn), + _divider(), + _meta(txn), + _divider(), + _itemsTable(txn), + _divider(), + _totals(txn), + _divider(), + _taxSummary(txn), + _divider(), + _payments(txn), + if (cart.customer != null) ...[ + _divider(), + _loyalty(txn), + ], + pw.SizedBox(height: 8), + _footer(txn), + ], + ), + ), + ); + + return doc.save(); + } + + // ------------------------------------------------------------- Sections + pw.Widget _header(SaleTransaction txn) => pw.Column(children: [ + pw.Text( + AppConstants.storeName.toUpperCase(), + style: pw.TextStyle(fontSize: 15, fontWeight: pw.FontWeight.bold), + textAlign: pw.TextAlign.center, + ), + pw.SizedBox(height: 2), + pw.Text( + AppConstants.storeAddress, + style: const pw.TextStyle(fontSize: 7), + textAlign: pw.TextAlign.center, + ), + pw.Text( + 'GSTIN: ${AppConstants.storeGstin} | ${AppConstants.storePhone}', + style: const pw.TextStyle(fontSize: 7), + textAlign: pw.TextAlign.center, + ), + pw.SizedBox(height: 4), + pw.Text( + 'TAX INVOICE', + style: pw.TextStyle(fontSize: 9, fontWeight: pw.FontWeight.bold), + ), + ]); + + pw.Widget _meta(SaleTransaction txn) { + final c = txn.customer; + return pw.Column(children: [ + _row('Invoice', txn.invoiceNumber), + _row('Date', Formatters.receiptStamp(txn.createdAt)), + _row('Cashier', txn.cashierName), + _row('Terminal', txn.terminalId), + _row('Customer', c == null ? 'Walk-in' : c.name), + if (c != null) _row('Mobile', Formatters.mobile(c.mobile)), + ]); + } + + pw.Widget _itemsTable(SaleTransaction txn) { + return pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.stretch, + children: [ + pw.Row(children: [ + pw.Expanded(flex: 5, child: _th('Item')), + pw.Expanded(flex: 2, child: _th('Qty', align: pw.TextAlign.center)), + pw.Expanded(flex: 3, child: _th('Rate', align: pw.TextAlign.right)), + pw.Expanded(flex: 3, child: _th('Amt', align: pw.TextAlign.right)), + ]), + pw.SizedBox(height: 2), + ...txn.cart.lines.map((line) => pw.Padding( + padding: const pw.EdgeInsets.symmetric(vertical: 1.5), + child: pw.Column(children: [ + pw.Row(children: [ + pw.Expanded(flex: 5, child: _td(line.product.name)), + pw.Expanded( + flex: 2, + child: _td( + _qty(line.quantity), + align: pw.TextAlign.center, + ), + ), + pw.Expanded( + flex: 3, + child: _td( + line.product.price.toStringAsFixed(2), + align: pw.TextAlign.right, + ), + ), + pw.Expanded( + flex: 3, + child: _td( + line.payable.toStringAsFixed(2), + align: pw.TextAlign.right, + ), + ), + ]), + if (line.discount.isActive) + pw.Row(children: [ + pw.Expanded( + child: _td( + ' ${line.discount.label} ' + '-${line.discountAmount.toStringAsFixed(2)}', + size: 6.5, + ), + ), + ]), + ]), + )), + ], + ); + } + + pw.Widget _totals(SaleTransaction txn) { + final cart = txn.cart; + return pw.Column(children: [ + _row('Items', '${cart.lineCount} (Qty ${_qty(cart.totalQuantity)})'), + _row('Subtotal', cart.subtotal.toStringAsFixed(2)), + if (cart.membershipDiscountAmount > 0) + _row( + '${cart.customer!.tier.label} discount', + '-${cart.membershipDiscountAmount.toStringAsFixed(2)}', + ), + if (cart.manualBillDiscountAmount > 0) + _row('Discount', '-${cart.manualBillDiscountAmount.toStringAsFixed(2)}'), + if (cart.loyaltyRedemptionValue > 0) + _row( + 'Points redeemed (${cart.pointsRedeemed})', + '-${cart.loyaltyRedemptionValue.toStringAsFixed(2)}', + ), + _row('Taxable value', cart.taxableAmount.toStringAsFixed(2)), + _row('CGST', cart.cgst.toStringAsFixed(2)), + _row('SGST', cart.sgst.toStringAsFixed(2)), + if (cart.roundOff != 0) + _row('Round off', cart.roundOff.toStringAsFixed(2)), + pw.SizedBox(height: 3), + pw.Row( + mainAxisAlignment: pw.MainAxisAlignment.spaceBetween, + children: [ + pw.Text('TOTAL', + style: pw.TextStyle(fontSize: 12, fontWeight: pw.FontWeight.bold)), + pw.Text( + '${AppConstants.currencySymbol}${txn.total.toStringAsFixed(2)}', + style: pw.TextStyle(fontSize: 12, fontWeight: pw.FontWeight.bold), + ), + ], + ), + if (cart.totalSavings > 0) ...[ + pw.SizedBox(height: 2), + pw.Text( + 'You saved ${AppConstants.currencySymbol}' + '${cart.totalSavings.toStringAsFixed(2)} on this bill', + style: pw.TextStyle(fontSize: 7.5, fontWeight: pw.FontWeight.bold), + textAlign: pw.TextAlign.center, + ), + ], + ]); + } + + pw.Widget _taxSummary(SaleTransaction txn) { + final breakdown = txn.cart.taxBreakdown.entries + .where((e) => e.value > 0) + .toList() + ..sort((a, b) => a.key.compareTo(b.key)); + + if (breakdown.isEmpty) { + return _td('All items zero-rated', size: 7); + } + + return pw.Column(children: [ + _th('GST Summary'), + ...breakdown.map((e) => _row( + 'GST @ ${(e.key * 100).toStringAsFixed(0)}%', + e.value.toStringAsFixed(2), + size: 7, + )), + ]); + } + + pw.Widget _payments(SaleTransaction txn) => pw.Column(children: [ + ...txn.payments.map((p) => _row( + p.method.label + + (p.reference != null ? ' (${p.reference})' : ''), + p.amount.toStringAsFixed(2), + )), + if (txn.changeDue > 0) + _row('Change returned', txn.changeDue.toStringAsFixed(2)), + ]); + + pw.Widget _loyalty(SaleTransaction txn) { + final c = txn.customer!; + final balance = c.loyaltyPoints - txn.pointsRedeemed + txn.pointsEarned; + return pw.Column(children: [ + _row('Points earned', '+${txn.pointsEarned}'), + if (txn.pointsRedeemed > 0) + _row('Points redeemed', '-${txn.pointsRedeemed}'), + _row('Points balance', '$balance'), + _row('Membership', c.tier.label), + ]); + } + + pw.Widget _footer(SaleTransaction txn) => pw.Column(children: [ + pw.BarcodeWidget( + barcode: pw.Barcode.code128(), + data: txn.invoiceNumber, + width: 140, + height: 34, + drawText: false, + ), + pw.SizedBox(height: 4), + pw.Text(txn.invoiceNumber, style: const pw.TextStyle(fontSize: 7)), + pw.SizedBox(height: 4), + pw.Text('Thank you for shopping with us!', + style: pw.TextStyle(fontSize: 8, fontWeight: pw.FontWeight.bold)), + pw.Text('Goods once sold are exchangeable within 7 days with this bill.', + style: const pw.TextStyle(fontSize: 6), + textAlign: pw.TextAlign.center), + pw.SizedBox(height: 2), + pw.Text('Powered by Nearle POS', style: const pw.TextStyle(fontSize: 6)), + ]); + + // -------------------------------------------------------------- Helpers + String _qty(double q) => + q % 1 == 0 ? q.toStringAsFixed(0) : q.toStringAsFixed(3); + + pw.Widget _divider() => pw.Padding( + padding: const pw.EdgeInsets.symmetric(vertical: 3), + child: pw.Divider(height: 0.5, borderStyle: pw.BorderStyle.dashed), + ); + + pw.Widget _th(String text, {pw.TextAlign align = pw.TextAlign.left}) => + pw.Text(text, + textAlign: align, + style: pw.TextStyle(fontSize: 7.5, fontWeight: pw.FontWeight.bold)); + + pw.Widget _td(String text, + {pw.TextAlign align = pw.TextAlign.left, double size = 7.5}) => + pw.Text(text, textAlign: align, style: pw.TextStyle(fontSize: size)); + + pw.Widget _row(String label, String value, {double size = 7.5}) => pw.Padding( + padding: const pw.EdgeInsets.symmetric(vertical: 0.8), + child: pw.Row( + mainAxisAlignment: pw.MainAxisAlignment.spaceBetween, + children: [ + pw.Text(label, style: pw.TextStyle(fontSize: size)), + pw.Text(value, style: pw.TextStyle(fontSize: size)), + ], + ), + ); + + // --------------------------------------------------------- Printing / IO + /// Silent print to the default roll printer — no OS dialog, so the cashier + /// is never blocked between sales. + Future printDirect(SaleTransaction txn) async { + try { + final bytes = await build(txn); + final printers = await Printing.listPrinters(); + final target = printers.where((p) => p.isDefault).firstOrNull ?? + (printers.isNotEmpty ? printers.first : null); + + if (target == null) return false; + + return await Printing.directPrintPdf( + printer: target, + onLayout: (_) async => bytes, + name: txn.invoiceNumber, + ); + } catch (e) { + debugPrint('Direct print failed: $e'); + return false; + } + } + + /// Falls back to the system print preview. + Future printWithDialog(SaleTransaction txn) async { + final bytes = await build(txn); + await Printing.layoutPdf( + onLayout: (_) async => bytes, + name: txn.invoiceNumber, + ); + } + + Future share(SaleTransaction txn) async { + final bytes = await build(txn); + await Printing.sharePdf(bytes: bytes, filename: '${txn.invoiceNumber}.pdf'); + } + + /// Opens the cash drawer via the ESC/POS kick pulse on pin 2. + Future openCashDrawer() async { + // ESC p m t1 t2 — sent to the receipt printer's serial passthrough. + // Wired up here as a no-op placeholder for the concrete driver. + debugPrint('Cash drawer kick: ESC p 0 25 250'); + } +} diff --git a/lib/core/services/sound_service.dart b/lib/core/services/sound_service.dart new file mode 100644 index 0000000..1f4fdcf --- /dev/null +++ b/lib/core/services/sound_service.dart @@ -0,0 +1,62 @@ +import 'dart:async'; + +import 'package:audioplayers/audioplayers.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import '../constants/asset_paths.dart'; + +/// Audible feedback for scanner billing. +/// +/// A cashier scanning at speed watches the customer, not the screen, so the +/// beep is the primary confirmation that an item registered. +class SoundService { + SoundService._(); + + static final SoundService instance = SoundService._(); + + final AudioPlayer _player = AudioPlayer(playerId: 'nearle_pos_sfx'); + bool _enabled = true; + + bool get enabled => _enabled; + set enabled(bool value) => _enabled = value; + + Future preload() async { + try { + await _player.setReleaseMode(ReleaseMode.stop); + } catch (e) { + debugPrint('SoundService preload failed: $e'); + } + } + + Future scanSuccess() => _play(AssetPaths.beepSuccess, haptic: true); + + Future scanError() => _play(AssetPaths.beepError, heavy: true); + + Future saleComplete() => _play(AssetPaths.chargeComplete); + + Future _play( + String asset, { + bool haptic = false, + bool heavy = false, + }) async { + if (!_enabled) return; + + // Haptics matter on tablets where the speaker may be muted on the floor. + if (heavy) { + unawaited(HapticFeedback.heavyImpact()); + } else if (haptic) { + unawaited(HapticFeedback.selectionClick()); + } + + try { + await _player.stop(); + await _player.play(AssetSource(asset.replaceFirst('assets/', ''))); + } catch (e) { + // Never let a missing sound file break the billing flow. + debugPrint('SoundService play failed for $asset: $e'); + } + } + + Future dispose() => _player.dispose(); +} diff --git a/lib/core/theme/app_colors.dart b/lib/core/theme/app_colors.dart new file mode 100644 index 0000000..4fc41d3 --- /dev/null +++ b/lib/core/theme/app_colors.dart @@ -0,0 +1,84 @@ +import 'package:flutter/material.dart'; + +/// Central colour palette for Nearle POS. +/// +/// Everything is derived from the brand primary `#662582` so that a single +/// change here re-skins the entire application. +class AppColors { + const AppColors._(); + + // ---------------------------------------------------------------- Brand + static const Color primary = Color(0xFF662582); + static const Color primaryDark = Color(0xFF4B1A60); + static const Color primaryLight = Color(0xFF8B4BA6); + static const Color primarySurface = Color(0xFFF4EDF7); + static const Color primaryBorder = Color(0xFFE3D3EC); + + static const MaterialColor primarySwatch = MaterialColor(0xFF662582, { + 50: Color(0xFFF4EDF7), + 100: Color(0xFFE3D3EC), + 200: Color(0xFFCDB1DC), + 300: Color(0xFFB68FCC), + 400: Color(0xFFA475C0), + 500: Color(0xFF662582), + 600: Color(0xFF5C2175), + 700: Color(0xFF4B1A60), + 800: Color(0xFF3B144B), + 900: Color(0xFF2A0E36), + }); + + // -------------------------------------------------------------- Neutrals + static const Color background = Color(0xFFF7F7F9); + static const Color surface = Color(0xFFFFFFFF); + static const Color surfaceAlt = Color(0xFFFAFAFC); + static const Color border = Color(0xFFE8E8EE); + static const Color divider = Color(0xFFEFEFF4); + + static const Color textPrimary = Color(0xFF17131C); + static const Color textSecondary = Color(0xFF6B6577); + static const Color textTertiary = Color(0xFF9A94A6); + static const Color textOnPrimary = Color(0xFFFFFFFF); + + // ------------------------------------------------------------- Semantic + static const Color success = Color(0xFF16A34A); + static const Color successSurface = Color(0xFFEAF7EF); + static const Color warning = Color(0xFFF59E0B); + static const Color warningSurface = Color(0xFFFEF6E7); + static const Color danger = Color(0xFFDC2626); + static const Color dangerSurface = Color(0xFFFDECEC); + static const Color info = Color(0xFF2563EB); + static const Color infoSurface = Color(0xFFEAF0FE); + + // ------------------------------------------------------- Membership tiers + static const Color tierBronze = Color(0xFFB08D57); + static const Color tierSilver = Color(0xFF8E96A3); + static const Color tierGold = Color(0xFFD4A017); + static const Color tierPlatinum = Color(0xFF4C5A6B); + + // ---------------------------------------------------------------- Effects + static const Color glassTint = Color(0x14662582); + + static const List shadowSm = [ + BoxShadow(color: Color(0x0D17131C), blurRadius: 6, offset: Offset(0, 2)), + ]; + + static const List shadowMd = [ + BoxShadow(color: Color(0x1417131C), blurRadius: 16, offset: Offset(0, 6)), + ]; + + static const List shadowLg = [ + BoxShadow(color: Color(0x1F17131C), blurRadius: 32, offset: Offset(0, 12)), + ]; + + static const LinearGradient primaryGradient = LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [Color(0xFF7A2E9A), Color(0xFF4B1A60)], + ); + + static const LinearGradient glassGradient = LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [Color(0x40FFFFFF), Color(0x0DFFFFFF)], + ); +} diff --git a/lib/core/theme/app_dimens.dart b/lib/core/theme/app_dimens.dart new file mode 100644 index 0000000..14ab9cb --- /dev/null +++ b/lib/core/theme/app_dimens.dart @@ -0,0 +1,83 @@ +import 'package:flutter/widgets.dart'; + +/// Spacing scale — 4pt grid. +class AppSpacing { + const AppSpacing._(); + + static const double xxs = 2; + static const double xs = 4; + static const double sm = 8; + static const double md = 12; + static const double lg = 16; + static const double xl = 20; + static const double xxl = 24; + static const double xxxl = 32; + static const double huge = 40; + static const double giant = 56; + + static const EdgeInsets pageDesktop = EdgeInsets.all(xxl); + static const EdgeInsets pageTablet = EdgeInsets.all(lg); + static const EdgeInsets card = EdgeInsets.all(lg); +} + +/// Corner radii — brand standard is 16. +class AppRadius { + const AppRadius._(); + + static const double xs = 6; + static const double sm = 10; + static const double md = 12; + static const double lg = 16; + static const double xl = 20; + static const double xxl = 28; + static const double pill = 999; + + static const BorderRadius brXs = BorderRadius.all(Radius.circular(xs)); + static const BorderRadius brSm = BorderRadius.all(Radius.circular(sm)); + static const BorderRadius brMd = BorderRadius.all(Radius.circular(md)); + static const BorderRadius brLg = BorderRadius.all(Radius.circular(lg)); + static const BorderRadius brXl = BorderRadius.all(Radius.circular(xl)); + static const BorderRadius brPill = BorderRadius.all(Radius.circular(pill)); +} + +/// Minimum sizes tuned for finger targets on tablets. +class AppSizes { + const AppSizes._(); + + static const double touchTarget = 48; + static const double buttonHeight = 52; + static const double buttonHeightLarge = 64; + static const double inputHeight = 56; + static const double headerHeight = 76; + static const double customerBarHeight = 72; + static const double navItemHeight = 46; + static const double productCardAspect = 0.86; + static const double keypadKeySize = 76; +} + +/// Motion durations & curves. +class AppMotion { + const AppMotion._(); + + static const Duration instant = Duration(milliseconds: 90); + static const Duration fast = Duration(milliseconds: 160); + static const Duration normal = Duration(milliseconds: 240); + static const Duration slow = Duration(milliseconds: 400); + + static const Curve emphasized = Curves.easeOutCubic; + static const Curve standard = Curves.easeInOut; + static const Curve bouncy = Curves.easeOutBack; +} + +/// Responsive breakpoints. +class AppBreakpoints { + const AppBreakpoints._(); + + static const double tabletPortrait = 920; + static const double tabletLandscape = 1300; + static const double desktop = 1650; + + static bool isCompact(double w) => w < tabletPortrait; + static bool isMedium(double w) => w >= tabletPortrait && w < desktop; + static bool isExpanded(double w) => w >= desktop; +} diff --git a/lib/core/theme/app_layout.dart b/lib/core/theme/app_layout.dart new file mode 100644 index 0000000..fdf0273 --- /dev/null +++ b/lib/core/theme/app_layout.dart @@ -0,0 +1,98 @@ +import 'package:flutter/widgets.dart'; + +/// How the left navigation should render at the current width. +enum SidebarMode { + /// Off-canvas; reachable through the page-header menu button. + drawer, + + /// Icons only, 84px. + rail, + + /// Icons plus labels and section headers, 252px. + expanded, +} + +/// How the bill should render at the current width. +enum BillingMode { + /// Bottom sheet, opened from the floating cart button. + sheet, + + /// Docked column on the right. + docked, +} + +/// Resolves every layout decision for the POS dashboard from a single width. +/// +/// Keeping this in one place means the sidebar, product grid and billing panel +/// can never disagree about which breakpoint they are in. +class PosLayout { + const PosLayout({ + required this.sidebar, + required this.billing, + required this.billingWidth, + required this.gridTileExtent, + required this.contentPadding, + }); + + final SidebarMode sidebar; + final BillingMode billing; + final double billingWidth; + + /// Maximum width of a product card; the grid fits as many as will fit. + final double gridTileExtent; + + final double contentPadding; + + static const double railWidth = 84; + static const double expandedWidth = 252; + + /// Below this the sidebar goes off-canvas. + static const double drawerBelow = 920; + + /// Below this the sidebar is icons-only. + static const double railBelow = 1300; + + /// Below this the bill becomes a bottom sheet. + static const double sheetBelow = 1120; + + /// Above this we have room for a wider bill and larger cards. + static const double wideAbove = 1650; + + factory PosLayout.of(BuildContext context) => + PosLayout.forWidth(MediaQuery.sizeOf(context).width); + + factory PosLayout.forWidth(double width) { + final sidebar = width < drawerBelow + ? SidebarMode.drawer + : (width < railBelow ? SidebarMode.rail : SidebarMode.expanded); + + final billing = + width < sheetBelow ? BillingMode.sheet : BillingMode.docked; + + final billingWidth = width >= wideAbove ? 440.0 : 380.0; + + // Cards stay finger-sized on tablets and grow a little on large desktops. + final tile = width < drawerBelow + ? 168.0 + : (width >= wideAbove ? 208.0 : 186.0); + + final padding = width < drawerBelow ? 16.0 : 24.0; + + return PosLayout( + sidebar: sidebar, + billing: billing, + billingWidth: billingWidth, + gridTileExtent: tile, + contentPadding: padding, + ); + } + + double get sidebarWidth => switch (sidebar) { + SidebarMode.drawer => 0, + SidebarMode.rail => railWidth, + SidebarMode.expanded => expandedWidth, + }; + + bool get sidebarIsDrawer => sidebar == SidebarMode.drawer; + bool get billingIsSheet => billing == BillingMode.sheet; +} diff --git a/lib/core/theme/app_theme.dart b/lib/core/theme/app_theme.dart new file mode 100644 index 0000000..cfa1f25 --- /dev/null +++ b/lib/core/theme/app_theme.dart @@ -0,0 +1,162 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'app_colors.dart'; +import 'app_dimens.dart'; +import 'app_typography.dart'; + +/// Builds the single source of truth [ThemeData] for Nearle POS. +class AppTheme { + const AppTheme._(); + + static ThemeData get light { + final colorScheme = ColorScheme.fromSeed( + seedColor: AppColors.primary, + primary: AppColors.primary, + onPrimary: AppColors.textOnPrimary, + secondary: AppColors.primaryLight, + surface: AppColors.surface, + onSurface: AppColors.textPrimary, + error: AppColors.danger, + brightness: Brightness.light, + ); + + return ThemeData( + useMaterial3: true, + colorScheme: colorScheme, + scaffoldBackgroundColor: AppColors.background, + textTheme: AppTypography.textTheme, + splashFactory: InkSparkle.splashFactory, + visualDensity: VisualDensity.standard, + + appBarTheme: AppBarTheme( + backgroundColor: AppColors.primary, + foregroundColor: AppColors.textOnPrimary, + elevation: 0, + centerTitle: false, + toolbarHeight: AppSizes.headerHeight, + systemOverlayStyle: SystemUiOverlayStyle.light, + titleTextStyle: AppTypography.textTheme.titleLarge + ?.copyWith(color: AppColors.textOnPrimary), + ), + + cardTheme: CardThemeData( + color: AppColors.surface, + elevation: 0, + margin: EdgeInsets.zero, + shape: RoundedRectangleBorder( + borderRadius: AppRadius.brLg, + side: const BorderSide(color: AppColors.border), + ), + ), + + dividerTheme: const DividerThemeData( + color: AppColors.divider, + thickness: 1, + space: 1, + ), + + elevatedButtonTheme: ElevatedButtonThemeData( + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primary, + foregroundColor: AppColors.textOnPrimary, + disabledBackgroundColor: AppColors.border, + disabledForegroundColor: AppColors.textTertiary, + minimumSize: const Size(0, AppSizes.buttonHeight), + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xxl), + elevation: 0, + shape: const RoundedRectangleBorder(borderRadius: AppRadius.brMd), + textStyle: AppTypography.textTheme.labelLarge, + ), + ), + + outlinedButtonTheme: OutlinedButtonThemeData( + style: OutlinedButton.styleFrom( + foregroundColor: AppColors.primary, + minimumSize: const Size(0, AppSizes.buttonHeight), + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xxl), + side: const BorderSide(color: AppColors.primaryBorder, width: 1.5), + shape: const RoundedRectangleBorder(borderRadius: AppRadius.brMd), + textStyle: AppTypography.textTheme.labelLarge, + ), + ), + + textButtonTheme: TextButtonThemeData( + style: TextButton.styleFrom( + foregroundColor: AppColors.primary, + minimumSize: const Size(0, AppSizes.touchTarget), + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), + shape: const RoundedRectangleBorder(borderRadius: AppRadius.brSm), + textStyle: AppTypography.textTheme.labelLarge, + ), + ), + + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: AppColors.surface, + contentPadding: const EdgeInsets.symmetric( + horizontal: AppSpacing.lg, + vertical: AppSpacing.lg, + ), + hintStyle: AppTypography.textTheme.bodyMedium + ?.copyWith(color: AppColors.textTertiary), + labelStyle: AppTypography.textTheme.bodyMedium + ?.copyWith(color: AppColors.textSecondary), + border: _inputBorder(AppColors.border), + enabledBorder: _inputBorder(AppColors.border), + focusedBorder: _inputBorder(AppColors.primary, width: 1.8), + errorBorder: _inputBorder(AppColors.danger), + focusedErrorBorder: _inputBorder(AppColors.danger, width: 1.8), + ), + + chipTheme: ChipThemeData( + backgroundColor: AppColors.surface, + selectedColor: AppColors.primary, + side: const BorderSide(color: AppColors.border), + labelStyle: AppTypography.textTheme.labelMedium, + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.lg, + vertical: AppSpacing.md, + ), + shape: const RoundedRectangleBorder(borderRadius: AppRadius.brPill), + ), + + dialogTheme: DialogThemeData( + backgroundColor: AppColors.surface, + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppRadius.xl), + ), + titleTextStyle: AppTypography.textTheme.headlineSmall, + ), + + snackBarTheme: SnackBarThemeData( + backgroundColor: AppColors.textPrimary, + contentTextStyle: AppTypography.textTheme.bodyMedium + ?.copyWith(color: Colors.white), + behavior: SnackBarBehavior.floating, + shape: const RoundedRectangleBorder(borderRadius: AppRadius.brMd), + ), + + scrollbarTheme: ScrollbarThemeData( + thickness: WidgetStateProperty.all(6), + radius: const Radius.circular(AppRadius.pill), + thumbColor: WidgetStateProperty.all(AppColors.primaryBorder), + ), + + pageTransitionsTheme: const PageTransitionsTheme(builders: { + TargetPlatform.windows: FadeUpwardsPageTransitionsBuilder(), + TargetPlatform.macOS: FadeUpwardsPageTransitionsBuilder(), + TargetPlatform.linux: FadeUpwardsPageTransitionsBuilder(), + TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), + }), + ); + } + + static OutlineInputBorder _inputBorder(Color color, {double width = 1}) { + return OutlineInputBorder( + borderRadius: AppRadius.brMd, + borderSide: BorderSide(color: color, width: width), + ); + } +} diff --git a/lib/core/theme/app_typography.dart b/lib/core/theme/app_typography.dart new file mode 100644 index 0000000..50cdb8e --- /dev/null +++ b/lib/core/theme/app_typography.dart @@ -0,0 +1,85 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; + +import 'app_colors.dart'; + +/// Poppins-based type scale. +/// +/// Poppins is geometric and runs slightly wide, so headings get negative +/// tracking to keep them compact in the sidebar and page header. POS screens +/// are read at arm's length, so body text starts at 15 rather than the +/// Material default of 14. +class AppTypography { + const AppTypography._(); + + static TextTheme get textTheme { + final base = GoogleFonts.poppinsTextTheme(); + + return base.copyWith( + displayLarge: _s(base.displayLarge, 44, FontWeight.w700, -1.2), + displayMedium: _s(base.displayMedium, 36, FontWeight.w700, -1.0), + displaySmall: _s(base.displaySmall, 30, FontWeight.w700, -0.8), + + headlineLarge: _s(base.headlineLarge, 28, FontWeight.w600, -0.7), + headlineMedium: _s(base.headlineMedium, 24, FontWeight.w600, -0.6), + headlineSmall: _s(base.headlineSmall, 20, FontWeight.w600, -0.4), + + titleLarge: _s(base.titleLarge, 18, FontWeight.w600, -0.3), + titleMedium: _s(base.titleMedium, 15.5, FontWeight.w600, -0.2), + titleSmall: _s(base.titleSmall, 13.5, FontWeight.w600, -0.1), + + bodyLarge: _s(base.bodyLarge, 15.5, FontWeight.w400, 0), + bodyMedium: _s(base.bodyMedium, 14.5, FontWeight.w400, 0), + bodySmall: _s(base.bodySmall, 12.5, FontWeight.w400, 0, + color: AppColors.textSecondary), + + labelLarge: _s(base.labelLarge, 14.5, FontWeight.w600, 0), + labelMedium: _s(base.labelMedium, 12.5, FontWeight.w600, 0.1), + labelSmall: _s(base.labelSmall, 10.5, FontWeight.w600, 0.6, + color: AppColors.textTertiary), + ); + } + + static TextStyle _s( + TextStyle? base, + double size, + FontWeight weight, + double tracking, { + Color color = AppColors.textPrimary, + }) { + return (base ?? const TextStyle()).copyWith( + fontSize: size, + fontWeight: weight, + letterSpacing: tracking, + color: color, + height: 1.35, + ); + } + + /// Tabular figures — essential so totals don't jitter as quantities change. + static TextStyle money(double size, + {FontWeight weight = FontWeight.w700, Color? color}) => + GoogleFonts.poppins( + fontSize: size, + fontWeight: weight, + color: color ?? AppColors.textPrimary, + letterSpacing: -0.5, + height: 1.15, + fontFeatures: const [FontFeature.tabularFigures()], + ); + + /// Fixed-pitch, used only for the receipt preview. + static TextStyle mono(double size, {Color? color}) => GoogleFonts.robotoMono( + fontSize: size, + color: color ?? AppColors.textTertiary, + letterSpacing: 0.2, + ); + + /// Small uppercase caption for sidebar section dividers. + static TextStyle sectionLabel() => GoogleFonts.poppins( + fontSize: 10.5, + fontWeight: FontWeight.w600, + letterSpacing: 1.0, + color: AppColors.textTertiary, + ); +} diff --git a/lib/core/utils/extensions.dart b/lib/core/utils/extensions.dart new file mode 100644 index 0000000..55f750b --- /dev/null +++ b/lib/core/utils/extensions.dart @@ -0,0 +1,59 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_dimens.dart'; + +extension BuildContextX on BuildContext { + ThemeData get theme => Theme.of(this); + TextTheme get text => Theme.of(this).textTheme; + ColorScheme get colors => Theme.of(this).colorScheme; + + Size get screen => MediaQuery.sizeOf(this); + double get screenWidth => MediaQuery.sizeOf(this).width; + double get screenHeight => MediaQuery.sizeOf(this).height; + + bool get isCompact => AppBreakpoints.isCompact(screenWidth); + bool get isMedium => AppBreakpoints.isMedium(screenWidth); + bool get isExpanded => AppBreakpoints.isExpanded(screenWidth); + + /// Picks a value appropriate to the current breakpoint. + T responsive({required T compact, T? medium, required T expanded}) { + if (isCompact) return compact; + if (isExpanded) return expanded; + return medium ?? expanded; + } + + void showSnack(String message, {Color? background}) { + ScaffoldMessenger.of(this) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar( + content: Text(message), + backgroundColor: background, + duration: const Duration(seconds: 2), + )); + } +} + +extension DoubleX on double { + /// Rounds to two decimals to avoid floating point drift in money maths. + double get asMoney => (this * 100).roundToDouble() / 100; + + /// Indian retail round-off to the nearest rupee. + double get roundedToRupee => roundToDouble(); +} + +extension StringX on String { + String get capitalized => + isEmpty ? this : '${this[0].toUpperCase()}${substring(1)}'; + + bool containsIgnoreCase(String other) => + toLowerCase().contains(other.toLowerCase()); +} + +extension IterableX on Iterable { + T? firstWhereOrNull(bool Function(T) test) { + for (final element in this) { + if (test(element)) return element; + } + return null; + } +} diff --git a/lib/core/utils/formatters.dart b/lib/core/utils/formatters.dart new file mode 100644 index 0000000..055e1ce --- /dev/null +++ b/lib/core/utils/formatters.dart @@ -0,0 +1,67 @@ +import 'package:intl/intl.dart'; + +import '../constants/app_constants.dart'; + +/// Currency, date and number formatting helpers. +class Formatters { + const Formatters._(); + + static final NumberFormat _currency = NumberFormat.currency( + locale: AppConstants.locale, + symbol: AppConstants.currencySymbol, + decimalDigits: 2, + ); + + static final NumberFormat _compactCurrency = NumberFormat.compactCurrency( + locale: AppConstants.locale, + symbol: AppConstants.currencySymbol, + decimalDigits: 1, + ); + + static final DateFormat _time = DateFormat('hh:mm a'); + static final DateFormat _date = DateFormat('dd MMM yyyy'); + static final DateFormat _dateTime = DateFormat('dd MMM yyyy, hh:mm a'); + static final DateFormat _receiptStamp = DateFormat('dd/MM/yyyy HH:mm:ss'); + + static String money(num value) => _currency.format(value); + static String moneyCompact(num value) => _compactCurrency.format(value); + + /// Amount without the symbol — used where the symbol is styled separately. + static String amount(num value) => value.toStringAsFixed(2); + + static String time(DateTime dt) => _time.format(dt); + static String date(DateTime dt) => _date.format(dt); + static String dateTime(DateTime dt) => _dateTime.format(dt); + static String receiptStamp(DateTime dt) => _receiptStamp.format(dt); + + static String percent(double fraction) => + '${(fraction * 100).toStringAsFixed(fraction * 100 % 1 == 0 ? 0 : 1)}%'; + + /// `9876543210` -> `98765 43210` + static String mobile(String raw) { + final digits = raw.replaceAll(RegExp(r'\D'), ''); + if (digits.length != 10) return raw; + return '${digits.substring(0, 5)} ${digits.substring(5)}'; + } + + /// Masks all but the last four digits for on-screen privacy. + static String maskedMobile(String raw) { + final digits = raw.replaceAll(RegExp(r'\D'), ''); + if (digits.length < 4) return raw; + return '${'\u2022' * (digits.length - 4)}${digits.substring(digits.length - 4)}'; + } + + static String initials(String name) { + final parts = name.trim().split(RegExp(r'\s+')).where((p) => p.isNotEmpty); + if (parts.isEmpty) return '?'; + if (parts.length == 1) return parts.first.substring(0, 1).toUpperCase(); + return (parts.first.substring(0, 1) + parts.last.substring(0, 1)) + .toUpperCase(); + } + + static String invoiceNumber(int sequence, DateTime date) { + final y = date.year.toString().substring(2); + final m = date.month.toString().padLeft(2, '0'); + return 'INV-$y$m-${sequence.toString().padLeft(5, '0')}'; + } +} diff --git a/lib/core/utils/validators.dart b/lib/core/utils/validators.dart new file mode 100644 index 0000000..e0c1a8a --- /dev/null +++ b/lib/core/utils/validators.dart @@ -0,0 +1,56 @@ +import '../constants/app_constants.dart'; + +/// Form field validators returning a message, or null when valid. +class Validators { + const Validators._(); + + static final RegExp _emailRe = + RegExp(r'^[\w.+-]+@([\w-]+\.)+[A-Za-z]{2,}$'); + static final RegExp _mobileRe = RegExp(r'^[6-9]\d{9}$'); + + static String? mobile(String? value) { + final v = (value ?? '').replaceAll(RegExp(r'\D'), ''); + if (v.isEmpty) return 'Mobile number is required'; + if (v.length != AppConstants.mobileNumberLength) { + return 'Enter all ${AppConstants.mobileNumberLength} digits'; + } + if (!_mobileRe.hasMatch(v)) return 'Enter a valid Indian mobile number'; + return null; + } + + static String? name(String? value) { + final v = (value ?? '').trim(); + if (v.isEmpty) return 'Customer name is required'; + if (v.length < 2) return 'Name is too short'; + if (v.length > 60) return 'Name is too long'; + return null; + } + + static String? emailOptional(String? value) { + final v = (value ?? '').trim(); + if (v.isEmpty) return null; + if (!_emailRe.hasMatch(v)) return 'Enter a valid email address'; + return null; + } + + static String? dobOptional(DateTime? value) { + if (value == null) return null; + final now = DateTime.now(); + if (value.isAfter(now)) return 'Date of birth cannot be in the future'; + if (now.year - value.year > 120) return 'Enter a valid date of birth'; + return null; + } + + static String? positiveAmount(String? value) { + final v = double.tryParse((value ?? '').trim()); + if (v == null) return 'Enter a valid amount'; + if (v <= 0) return 'Amount must be greater than zero'; + return null; + } + + static bool isLikelyBarcode(String value) { + final v = value.trim(); + return v.length >= AppConstants.minBarcodeLength && + RegExp(r'^\d+$').hasMatch(v); + } +} diff --git a/lib/core/widgets/empty_state.dart b/lib/core/widgets/empty_state.dart new file mode 100644 index 0000000..c7c35f2 --- /dev/null +++ b/lib/core/widgets/empty_state.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_colors.dart'; +import '../theme/app_dimens.dart'; + +class EmptyState extends StatelessWidget { + const EmptyState({ + super.key, + required this.title, + this.message, + this.emoji = '🛒', + this.action, + this.compact = false, + }); + + final String title; + final String? message; + final String emoji; + final Widget? action; + final bool compact; + + @override + Widget build(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.all(AppSpacing.xxl), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: compact ? 64 : 96, + height: compact ? 64 : 96, + decoration: const BoxDecoration( + color: AppColors.primarySurface, + shape: BoxShape.circle, + ), + alignment: Alignment.center, + child: Text(emoji, + style: TextStyle(fontSize: compact ? 28 : 40)), + ), + SizedBox(height: compact ? AppSpacing.lg : AppSpacing.xxl), + Text( + title, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: compact ? 15 : 18, + fontWeight: FontWeight.w700, + color: AppColors.textPrimary, + ), + ), + if (message != null) ...[ + const SizedBox(height: AppSpacing.sm), + Text( + message!, + textAlign: TextAlign.center, + style: const TextStyle( + fontSize: 14, + color: AppColors.textSecondary, + height: 1.45, + ), + ), + ], + if (action != null) ...[ + const SizedBox(height: AppSpacing.xxl), + action!, + ], + ], + ), + ), + ); + } +} diff --git a/lib/core/widgets/glass_card.dart b/lib/core/widgets/glass_card.dart new file mode 100644 index 0000000..dc787a4 --- /dev/null +++ b/lib/core/widgets/glass_card.dart @@ -0,0 +1,85 @@ +import 'dart:ui'; + +import 'package:flutter/material.dart'; + +import '../theme/app_colors.dart'; +import '../theme/app_dimens.dart'; + +/// Glassmorphism-inspired surface used for elevated panels and product cards. +class GlassCard extends StatelessWidget { + const GlassCard({ + super.key, + required this.child, + this.padding = AppSpacing.card, + this.radius = AppRadius.lg, + this.blur = 0, + this.tinted = false, + this.borderColor, + this.shadows, + this.onTap, + this.width, + this.height, + }); + + final Widget child; + final EdgeInsetsGeometry padding; + final double radius; + + /// Backdrop blur strength. Zero renders an opaque card, which is cheaper and + /// is the right default for the dense product grid. + final double blur; + + final bool tinted; + final Color? borderColor; + final List? shadows; + final VoidCallback? onTap; + final double? width; + final double? height; + + @override + Widget build(BuildContext context) { + final borderRadius = BorderRadius.circular(radius); + + Widget surface = AnimatedContainer( + duration: AppMotion.fast, + width: width, + height: height, + padding: padding, + decoration: BoxDecoration( + color: tinted + ? AppColors.primarySurface.withValues(alpha: blur > 0 ? 0.75 : 1) + : AppColors.surface.withValues(alpha: blur > 0 ? 0.78 : 1), + borderRadius: borderRadius, + border: Border.all( + color: borderColor ?? + (tinted ? AppColors.primaryBorder : AppColors.border), + ), + boxShadow: shadows ?? AppColors.shadowSm, + ), + child: child, + ); + + if (blur > 0) { + surface = ClipRRect( + borderRadius: borderRadius, + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur), + child: surface, + ), + ); + } + + if (onTap == null) return surface; + + return Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + borderRadius: borderRadius, + splashColor: AppColors.primary.withValues(alpha: 0.08), + highlightColor: AppColors.primary.withValues(alpha: 0.04), + child: surface, + ), + ); + } +} diff --git a/lib/core/widgets/numeric_keypad.dart b/lib/core/widgets/numeric_keypad.dart new file mode 100644 index 0000000..d9fccee --- /dev/null +++ b/lib/core/widgets/numeric_keypad.dart @@ -0,0 +1,146 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../theme/app_colors.dart'; +import '../theme/app_dimens.dart'; + +/// Large on-screen keypad for mobile numbers and cash amounts. +class NumericKeypad extends StatelessWidget { + const NumericKeypad({ + super.key, + required this.onKey, + required this.onBackspace, + this.onClear, + this.onSubmit, + this.submitLabel, + this.allowDecimal = false, + this.maxWidth = 360, + }); + + final ValueChanged onKey; + final VoidCallback onBackspace; + final VoidCallback? onClear; + final VoidCallback? onSubmit; + final String? submitLabel; + final bool allowDecimal; + final double maxWidth; + + @override + Widget build(BuildContext context) { + return ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxWidth), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final row in const [ + ['1', '2', '3'], + ['4', '5', '6'], + ['7', '8', '9'], + ]) + _row(row.map((d) => _digit(d)).toList()), + _row([ + allowDecimal + ? _digit('.') + : _action( + icon: Icons.clear_all_rounded, + onTap: onClear, + tone: AppColors.textSecondary, + ), + _digit('0'), + _action( + icon: Icons.backspace_outlined, + onTap: onBackspace, + tone: AppColors.danger, + ), + ]), + if (onSubmit != null) ...[ + const SizedBox(height: AppSpacing.md), + SizedBox( + width: double.infinity, + height: AppSizes.buttonHeight, + child: FilledButton.icon( + onPressed: onSubmit, + icon: const Icon(Icons.check_rounded), + label: Text(submitLabel ?? 'Done'), + ), + ), + ], + ], + ), + ); + } + + Widget _row(List children) => Padding( + padding: const EdgeInsets.only(bottom: AppSpacing.md), + child: Row( + children: [ + for (var i = 0; i < children.length; i++) ...[ + Expanded(child: children[i]), + if (i != children.length - 1) + const SizedBox(width: AppSpacing.md), + ], + ], + ), + ); + + Widget _digit(String value) => _Key( + onTap: () { + HapticFeedback.selectionClick(); + onKey(value); + }, + child: Text( + value, + style: const TextStyle( + fontSize: 26, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + ), + ), + ); + + Widget _action({ + required IconData icon, + required VoidCallback? onTap, + required Color tone, + }) => + _Key( + onTap: onTap == null + ? null + : () { + HapticFeedback.lightImpact(); + onTap(); + }, + child: Icon(icon, size: 24, color: tone), + ); +} + +class _Key extends StatelessWidget { + const _Key({required this.child, this.onTap}); + + final Widget child; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: AppSizes.keypadKeySize, + child: Material( + color: AppColors.surface, + borderRadius: AppRadius.brMd, + child: InkWell( + onTap: onTap, + borderRadius: AppRadius.brMd, + splashColor: AppColors.primary.withValues(alpha: 0.1), + child: Container( + alignment: Alignment.center, + decoration: BoxDecoration( + borderRadius: AppRadius.brMd, + border: Border.all(color: AppColors.border), + ), + child: child, + ), + ), + ), + ); + } +} diff --git a/lib/core/widgets/primary_button.dart b/lib/core/widgets/primary_button.dart new file mode 100644 index 0000000..9e7fa62 --- /dev/null +++ b/lib/core/widgets/primary_button.dart @@ -0,0 +1,126 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_colors.dart'; +import '../theme/app_dimens.dart'; + +enum ButtonTone { primary, neutral, success, danger, ghost } + +/// Large, touch-first action button with built-in busy state. +class PrimaryButton extends StatelessWidget { + const PrimaryButton({ + super.key, + required this.label, + this.onPressed, + this.icon, + this.tone = ButtonTone.primary, + this.expanded = true, + this.large = false, + this.busy = false, + this.trailing, + }); + + final String label; + final VoidCallback? onPressed; + final IconData? icon; + final ButtonTone tone; + final bool expanded; + final bool large; + final bool busy; + + /// Optional right-aligned widget, typically the bill total. + final Widget? trailing; + + @override + Widget build(BuildContext context) { + final enabled = onPressed != null && !busy; + final (bg, fg, border) = _palette; + final height = + large ? AppSizes.buttonHeightLarge : AppSizes.buttonHeight; + + final content = busy + ? SizedBox( + height: 22, + width: 22, + child: CircularProgressIndicator(strokeWidth: 2.4, color: fg), + ) + : Row( + mainAxisSize: expanded ? MainAxisSize.max : MainAxisSize.min, + mainAxisAlignment: trailing != null + ? MainAxisAlignment.spaceBetween + : MainAxisAlignment.center, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (icon != null) ...[ + Icon(icon, size: large ? 24 : 20, color: fg), + const SizedBox(width: AppSpacing.sm), + ], + Flexible( + child: Text( + label, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: fg, + fontSize: large ? 19 : 16, + fontWeight: FontWeight.w700, + letterSpacing: 0.1, + ), + ), + ), + ], + ), + if (trailing != null) trailing!, + ], + ); + + return SizedBox( + width: expanded ? double.infinity : null, + height: height, + child: Material( + color: enabled ? bg : AppColors.border, + borderRadius: AppRadius.brMd, + child: InkWell( + onTap: enabled ? onPressed : null, + borderRadius: AppRadius.brMd, + child: Container( + padding: EdgeInsets.symmetric( + horizontal: large ? AppSpacing.xxl : AppSpacing.xl, + ), + decoration: BoxDecoration( + borderRadius: AppRadius.brMd, + border: border == null + ? null + : Border.all(color: border, width: 1.5), + ), + alignment: Alignment.center, + child: DefaultTextStyle.merge( + style: TextStyle(color: enabled ? fg : AppColors.textTertiary), + child: content, + ), + ), + ), + ), + ); + } + + (Color, Color, Color?) get _palette => switch (tone) { + ButtonTone.primary => ( + AppColors.primary, + AppColors.textOnPrimary, + null + ), + ButtonTone.success => (AppColors.success, Colors.white, null), + ButtonTone.danger => (AppColors.danger, Colors.white, null), + ButtonTone.neutral => ( + AppColors.surface, + AppColors.textPrimary, + AppColors.border + ), + ButtonTone.ghost => ( + AppColors.primarySurface, + AppColors.primary, + AppColors.primaryBorder + ), + }; +} diff --git a/lib/core/widgets/status_pill.dart b/lib/core/widgets/status_pill.dart new file mode 100644 index 0000000..fdf3a89 --- /dev/null +++ b/lib/core/widgets/status_pill.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_colors.dart'; +import '../theme/app_dimens.dart'; +import '../../domain/entities/customer.dart'; + +/// Compact labelled badge — stock states, tiers, live indicator. +class StatusPill extends StatelessWidget { + const StatusPill({ + super.key, + required this.label, + this.color = AppColors.primary, + this.background, + this.icon, + this.dense = false, + }); + + final String label; + final Color color; + final Color? background; + final IconData? icon; + final bool dense; + + factory StatusPill.tier(MembershipTier tier, {bool dense = false}) { + final color = switch (tier) { + MembershipTier.bronze => AppColors.tierBronze, + MembershipTier.silver => AppColors.tierSilver, + MembershipTier.gold => AppColors.tierGold, + MembershipTier.platinum => AppColors.tierPlatinum, + }; + return StatusPill( + label: tier.label.toUpperCase(), + color: color, + background: color.withValues(alpha: 0.12), + dense: dense, + ); + } + + factory StatusPill.stock(double stock, {required int lowThreshold}) { + if (stock <= 0) { + return const StatusPill( + label: 'Out of stock', + color: AppColors.danger, + background: AppColors.dangerSurface, + dense: true, + ); + } + if (stock <= lowThreshold) { + return StatusPill( + label: '${stock.toStringAsFixed(0)} left', + color: AppColors.warning, + background: AppColors.warningSurface, + dense: true, + ); + } + return StatusPill( + label: '${stock.toStringAsFixed(0)} in stock', + color: AppColors.textTertiary, + background: Colors.transparent, + dense: true, + ); + } + + @override + Widget build(BuildContext context) { + return Container( + padding: EdgeInsets.symmetric( + horizontal: dense ? AppSpacing.sm : AppSpacing.md, + vertical: dense ? 3 : AppSpacing.xs + 2, + ), + decoration: BoxDecoration( + color: background ?? color.withValues(alpha: 0.12), + borderRadius: AppRadius.brPill, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (icon != null) ...[ + Icon(icon, size: dense ? 11 : 13, color: color), + const SizedBox(width: AppSpacing.xs), + ], + Text( + label, + style: TextStyle( + color: color, + fontSize: dense ? 10.5 : 12, + fontWeight: FontWeight.w700, + letterSpacing: 0.3, + ), + ), + ], + ), + ); + } +} diff --git a/lib/data/datasources/local_store.dart b/lib/data/datasources/local_store.dart new file mode 100644 index 0000000..ae6c98d --- /dev/null +++ b/lib/data/datasources/local_store.dart @@ -0,0 +1,136 @@ +import '../../domain/entities/customer.dart'; +import '../../domain/entities/product.dart'; +import '../../domain/entities/sync_event.dart'; +import '../../domain/entities/transaction.dart'; +import 'seed_data.dart'; + +/// On-terminal storage. +/// +/// The terminal starts with an **empty catalogue**: nothing can be billed +/// until the cashier imports products. Everything after that — sales, parked +/// bills, queued events — lives here and survives without a connection. +/// +/// Swapping this for Hive or SQLite changes nothing above the data layer. +class LocalStore { + LocalStore._(); + + static final LocalStore instance = LocalStore._(); + + final Map _products = {}; + final Map _customers = {}; + final List _transactions = []; + final List _parked = []; + final List _events = []; + + int _invoiceSequence = 0; + + DateTime? _lastImportAt; + String? _catalogueRevision; + + /// Nothing to seed — the catalogue arrives via import. + Future init() async {} + + /// Test helper. Clears everything and optionally loads the demo catalogue + /// so fixtures don't have to run an import first. + Future reset({bool withCatalogue = false}) async { + _products.clear(); + _customers.clear(); + _transactions.clear(); + _parked.clear(); + _events.clear(); + _invoiceSequence = 0; + _lastImportAt = null; + _catalogueRevision = null; + + if (withCatalogue) { + importCatalogue( + products: SeedData.products(), + customers: SeedData.customers(), + revision: 'seed', + at: DateTime.now(), + ); + } + } + + // -------------------------------------------------------------- Catalogue + /// True once a catalogue has been pulled. The POS refuses to bill until so. + bool get hasCatalogue => _products.isNotEmpty; + + DateTime? get lastImportAt => _lastImportAt; + String? get catalogueRevision => _catalogueRevision; + + /// Replaces the catalogue wholesale. + /// + /// Stock levels already adjusted by local sales are preserved for products + /// that survive the re-import, so importing mid-shift does not resurrect + /// stock that has been sold. + void importCatalogue({ + required List products, + required List customers, + required String revision, + required DateTime at, + }) { + final priorStock = { + for (final p in _products.values) p.id: p.stock, + }; + + _products + ..clear() + ..addEntries(products.map((p) { + final held = priorStock[p.id]; + return MapEntry(p.id, held == null ? p : p.copyWith(stock: held)); + })); + + // Locally registered customers must not be wiped by a server pull. + for (final c in customers) { + _customers.putIfAbsent(c.id, () => c); + } + + _lastImportAt = at; + _catalogueRevision = revision; + } + + // --------------------------------------------------------------- Products + List get products => _products.values.toList(growable: false); + + void putProduct(Product p) => _products[p.id] = p; + + Product? productById(String id) => _products[id]; + + // -------------------------------------------------------------- Customers + List get customers => _customers.values.toList(growable: false); + + void putCustomer(Customer c) => _customers[c.id] = c; + + Customer? customerById(String id) => _customers[id]; + + // ----------------------------------------------------------- Transactions + List get transactions => + List.unmodifiable(_transactions.reversed); + + void addTransaction(SaleTransaction t) => _transactions.add(t); + + int nextInvoiceSequence() => ++_invoiceSequence; + + // ------------------------------------------------------------ Parked bills + List get parked => List.unmodifiable(_parked); + + void addParked(ParkedBill b) => _parked.add(b); + + void removeParked(String id) => _parked.removeWhere((b) => b.id == id); + + // ------------------------------------------------------------ Sync events + List get events => List.unmodifiable(_events.reversed); + + void addEvent(SyncEvent e) => _events.add(e); + + /// Updates in place. Events are never removed, so a failed push stays + /// visible and retryable. + void updateEvent(SyncEvent e) { + final i = _events.indexWhere((x) => x.id == e.id); + if (i >= 0) _events[i] = e; + } + + bool get hasUnsyncedEvents => + _events.any((e) => e.status != SyncStatus.synced); +} diff --git a/lib/data/datasources/remote_catalogue_source.dart b/lib/data/datasources/remote_catalogue_source.dart new file mode 100644 index 0000000..73832bb --- /dev/null +++ b/lib/data/datasources/remote_catalogue_source.dart @@ -0,0 +1,98 @@ +import '../../domain/entities/customer.dart'; +import '../../domain/entities/product.dart'; +import 'seed_data.dart'; + +/// What one catalogue pull returns. +class CatalogueSnapshot { + const CatalogueSnapshot({ + required this.products, + required this.customers, + required this.fetchedAt, + required this.revision, + }); + + final List products; + final List customers; + final DateTime fetchedAt; + + /// Server-side catalogue version, shown so the cashier can tell whether a + /// re-import actually changed anything. + final String revision; +} + +/// Raised when the catalogue cannot be pulled. +class CatalogueSyncException implements Exception { + const CatalogueSyncException(this.message); + + final String message; + + @override + String toString() => message; +} + +/// Stands in for the back-office catalogue API. +/// +/// The real implementation would issue an HTTP request; the contract is the +/// same, so only this class changes. +class RemoteCatalogueSource { + RemoteCatalogueSource(); + + /// Flipped from Settings to exercise the offline path. + bool simulateOffline = false; + + /// Streams progress so the import screen can show a real bar rather than an + /// indeterminate spinner. + Future fetch({ + void Function(double progress, String stage)? onProgress, + }) async { + const stages = [ + (0.15, 'Contacting server…'), + (0.35, 'Authorising terminal…'), + (0.60, 'Downloading products…'), + (0.85, 'Downloading customers…'), + (1.00, 'Writing to local storage…'), + ]; + + for (final (progress, stage) in stages) { + await Future.delayed(const Duration(milliseconds: 320)); + + if (simulateOffline) { + throw const CatalogueSyncException( + 'No connection to the catalogue server. ' + 'Check the network and try again.', + ); + } + + onProgress?.call(progress, stage); + } + + return CatalogueSnapshot( + products: SeedData.products(), + customers: SeedData.customers(), + fetchedAt: DateTime.now(), + revision: 'rev-${DateTime.now().millisecondsSinceEpoch % 100000}', + ); + } +} + +/// Stands in for the back-office reporting API. +class RemoteReportSink { + RemoteReportSink(); + + bool simulateOffline = false; + + /// Pushes one payload. Throws on failure so the caller can keep the event + /// queued rather than marking it sent. + Future push(Map payload) async { + await Future.delayed(const Duration(milliseconds: 900)); + + if (simulateOffline) { + throw const CatalogueSyncException( + 'Could not reach the reporting server. ' + 'The report is still saved on this terminal.', + ); + } + + return 'ACK-${DateTime.now().millisecondsSinceEpoch % 1000000}'; + } +} diff --git a/lib/data/datasources/seed_data.dart b/lib/data/datasources/seed_data.dart new file mode 100644 index 0000000..11d51c5 --- /dev/null +++ b/lib/data/datasources/seed_data.dart @@ -0,0 +1,542 @@ +import '../../domain/entities/customer.dart'; +import '../../domain/entities/product.dart'; + +/// Demo catalogue and customer book. +/// +/// Barcodes are valid 13-digit EAN strings beginning with the Indian GS1 +/// prefix `890`, so a real scanner can be tested against this data. +class SeedData { + const SeedData._(); + + static List products() => const [ + // ------------------------------------------------------------ Dairy + Product( + id: 'p001', + name: 'Amul Milk 1L', + barcode: '8901234500011', + sku: 'DRY-MLK-1000', + category: ProductCategory.dairy, + price: 62, + mrp: 66, + stock: 50, + emoji: '🥛', + unit: UnitOfMeasure.litre, + gstRate: 0.05, + brand: 'Amul', + ), + Product( + id: 'p002', + name: 'Amul Butter 500g', + barcode: '8901234500028', + sku: 'DRY-BTR-0500', + category: ProductCategory.dairy, + price: 245, + mrp: 265, + stock: 30, + emoji: '🧈', + gstRate: 0.12, + brand: 'Amul', + ), + Product( + id: 'p003', + name: 'Curd 400g', + barcode: '8901234500035', + sku: 'DRY-CRD-0400', + category: ProductCategory.dairy, + price: 48, + mrp: 52, + stock: 40, + emoji: '🥣', + gstRate: 0.05, + brand: 'Nandini', + ), + Product( + id: 'p004', + name: 'Paneer 200g', + barcode: '8901234500042', + sku: 'DRY-PNR-0200', + category: ProductCategory.dairy, + price: 90, + stock: 20, + emoji: '🧀', + gstRate: 0.05, + brand: 'Milky Mist', + ), + Product( + id: 'p005', + name: 'Cheese Slices 200g', + barcode: '8901234500059', + sku: 'DRY-CHS-0200', + category: ProductCategory.dairy, + price: 135, + mrp: 145, + stock: 25, + emoji: '🧀', + gstRate: 0.12, + brand: 'Britannia', + ), + + // ---------------------------------------------------------- Grocery + Product( + id: 'p010', + name: 'Basmati Rice 1kg', + barcode: '8901234500110', + sku: 'GRO-RCE-1000', + category: ProductCategory.grocery, + price: 180, + mrp: 199, + stock: 4, + emoji: '🍚', + unit: UnitOfMeasure.kilogram, + gstRate: 0.05, + brand: 'India Gate', + ), + Product( + id: 'p011', + name: 'Fortune Oil 1L', + barcode: '8901234500127', + sku: 'GRO-OIL-1000', + category: ProductCategory.grocery, + price: 145, + mrp: 160, + stock: 60, + emoji: '🛢️', + unit: UnitOfMeasure.litre, + gstRate: 0.05, + brand: 'Fortune', + ), + Product( + id: 'p012', + name: 'Toor Dal 500g', + barcode: '8901234500134', + sku: 'GRO-DAL-0500', + category: ProductCategory.grocery, + price: 90, + stock: 45, + emoji: '🫘', + gstRate: 0.05, + brand: 'Tata Sampann', + ), + Product( + id: 'p013', + name: 'Aashirvaad Atta 5kg', + barcode: '8901234500141', + sku: 'GRO-ATA-5000', + category: ProductCategory.grocery, + price: 285, + mrp: 310, + stock: 35, + emoji: '🌾', + unit: UnitOfMeasure.kilogram, + gstRate: 0.05, + brand: 'Aashirvaad', + ), + Product( + id: 'p014', + name: 'Sugar 1kg', + barcode: '8901234500158', + sku: 'GRO-SGR-1000', + category: ProductCategory.grocery, + price: 48, + stock: 80, + emoji: '🍬', + unit: UnitOfMeasure.kilogram, + gstRate: 0.05, + ), + Product( + id: 'p015', + name: 'Maggi 2-min', + barcode: '8901234500165', + sku: 'GRO-MAG-0070', + category: ProductCategory.grocery, + price: 14, + stock: 120, + emoji: '🍜', + gstRate: 0.12, + brand: 'Nestlé', + ), + Product( + id: 'p016', + name: 'Tata Salt 1kg', + barcode: '8901234500172', + sku: 'GRO-SLT-1000', + category: ProductCategory.grocery, + price: 28, + stock: 95, + emoji: '🧂', + unit: UnitOfMeasure.kilogram, + gstRate: 0.05, + brand: 'Tata', + ), + + // -------------------------------------------------------- Beverages + Product( + id: 'p020', + name: 'Coca-Cola 600ml', + barcode: '8901234500219', + sku: 'BEV-COK-0600', + category: ProductCategory.beverages, + price: 40, + stock: 80, + emoji: '🥤', + unit: UnitOfMeasure.millilitre, + gstRate: 0.28, + brand: 'Coca-Cola', + ), + Product( + id: 'p021', + name: 'Frooti 250ml', + barcode: '8901234500226', + sku: 'BEV-FRT-0250', + category: ProductCategory.beverages, + price: 15, + stock: 100, + emoji: '🥭', + gstRate: 0.12, + brand: 'Parle Agro', + ), + Product( + id: 'p022', + name: 'Bisleri 1L', + barcode: '8901234500233', + sku: 'BEV-WTR-1000', + category: ProductCategory.beverages, + price: 20, + stock: 150, + emoji: '💧', + unit: UnitOfMeasure.litre, + gstRate: 0.18, + brand: 'Bisleri', + ), + Product( + id: 'p023', + name: 'Red Bull 250ml', + barcode: '8901234500240', + sku: 'BEV-RBL-0250', + category: ProductCategory.beverages, + price: 125, + stock: 40, + emoji: '🔋', + gstRate: 0.28, + brand: 'Red Bull', + ), + Product( + id: 'p024', + name: 'Bru Coffee 100g', + barcode: '8901234500257', + sku: 'BEV-COF-0100', + category: ProductCategory.beverages, + price: 165, + mrp: 180, + stock: 30, + emoji: '☕', + gstRate: 0.18, + brand: 'Bru', + ), + + // ----------------------------------------------------------- Snacks + Product( + id: 'p030', + name: 'Parle-G 800g', + barcode: '8901234500318', + sku: 'SNK-PGB-0800', + category: ProductCategory.snacks, + price: 40, + stock: 90, + emoji: '🍪', + gstRate: 0.18, + brand: 'Parle', + ), + Product( + id: 'p031', + name: "Lay's Chips 26g", + barcode: '8901234500325', + sku: 'SNK-LAY-0026', + category: ProductCategory.snacks, + price: 20, + stock: 110, + emoji: '🥔', + gstRate: 0.18, + brand: "Lay's", + ), + Product( + id: 'p032', + name: 'Dairy Milk 55g', + barcode: '8901234500332', + sku: 'SNK-DMK-0055', + category: ProductCategory.snacks, + price: 45, + stock: 75, + emoji: '🍫', + gstRate: 0.18, + brand: 'Cadbury', + ), + Product( + id: 'p033', + name: 'Good Day 200g', + barcode: '8901234500349', + sku: 'SNK-GDY-0200', + category: ProductCategory.snacks, + price: 35, + stock: 85, + emoji: '🍪', + gstRate: 0.18, + brand: 'Britannia', + ), + Product( + id: 'p034', + name: 'Haldiram Mixture 200g', + barcode: '8901234500356', + sku: 'SNK-HMX-0200', + category: ProductCategory.snacks, + price: 55, + stock: 60, + emoji: '🥜', + gstRate: 0.12, + brand: 'Haldiram', + ), + + // ---------------------------------------------------- Personal care + Product( + id: 'p040', + name: 'Colgate 200g', + barcode: '8901234500417', + sku: 'PER-CLG-0200', + category: ProductCategory.personalCare, + price: 110, + mrp: 125, + stock: 55, + emoji: '🪥', + gstRate: 0.18, + brand: 'Colgate', + ), + Product( + id: 'p041', + name: 'Dove Soap 100g', + barcode: '8901234500424', + sku: 'PER-DVE-0100', + category: ProductCategory.personalCare, + price: 65, + stock: 70, + emoji: '🧼', + gstRate: 0.18, + brand: 'Dove', + ), + Product( + id: 'p042', + name: 'Head & Shoulders 340ml', + barcode: '8901234500431', + sku: 'PER-HNS-0340', + category: ProductCategory.personalCare, + price: 385, + mrp: 420, + stock: 25, + emoji: '🧴', + gstRate: 0.18, + brand: 'P&G', + ), + Product( + id: 'p043', + name: 'Nivea Lotion 200ml', + barcode: '8901234500448', + sku: 'PER-NVA-0200', + category: ProductCategory.personalCare, + price: 240, + stock: 30, + emoji: '🧴', + gstRate: 0.18, + brand: 'Nivea', + ), + + // -------------------------------------------------------- Household + Product( + id: 'p050', + name: 'Surf Excel 1kg', + barcode: '8901234500516', + sku: 'HSE-SRF-1000', + category: ProductCategory.household, + price: 165, + mrp: 180, + stock: 45, + emoji: '🧺', + unit: UnitOfMeasure.kilogram, + gstRate: 0.18, + brand: 'Surf Excel', + ), + Product( + id: 'p051', + name: 'Vim Bar 300g', + barcode: '8901234500523', + sku: 'HSE-VIM-0300', + category: ProductCategory.household, + price: 30, + stock: 90, + emoji: '🧽', + gstRate: 0.18, + brand: 'Vim', + ), + Product( + id: 'p052', + name: 'Harpic 500ml', + barcode: '8901234500530', + sku: 'HSE-HRP-0500', + category: ProductCategory.household, + price: 98, + stock: 40, + emoji: '🧴', + gstRate: 0.18, + brand: 'Harpic', + ), + Product( + id: 'p053', + name: 'Garbage Bags 30pc', + barcode: '8901234500547', + sku: 'HSE-GBG-0030', + category: ProductCategory.household, + price: 145, + stock: 35, + emoji: '🗑️', + gstRate: 0.18, + ), + + // ----------------------------------------------------------- Fruits + Product( + id: 'p060', + name: 'Banana 1kg', + barcode: '8901234500615', + sku: 'FRT-BAN-1000', + category: ProductCategory.fruits, + price: 55, + stock: 40, + emoji: '🍌', + unit: UnitOfMeasure.kilogram, + gstRate: 0, + ), + Product( + id: 'p061', + name: 'Apple Shimla 1kg', + barcode: '8901234500622', + sku: 'FRT-APL-1000', + category: ProductCategory.fruits, + price: 180, + stock: 25, + emoji: '🍎', + unit: UnitOfMeasure.kilogram, + gstRate: 0, + ), + Product( + id: 'p062', + name: 'Alphonso Mango 1kg', + barcode: '8901234500639', + sku: 'FRT-MNG-1000', + category: ProductCategory.fruits, + price: 320, + stock: 15, + emoji: '🥭', + unit: UnitOfMeasure.kilogram, + gstRate: 0, + ), + + // ------------------------------------------------------- Vegetables + Product( + id: 'p070', + name: 'Tomato 1kg', + barcode: '8901234500714', + sku: 'VEG-TOM-1000', + category: ProductCategory.vegetables, + price: 40, + stock: 50, + emoji: '🍅', + unit: UnitOfMeasure.kilogram, + gstRate: 0, + ), + Product( + id: 'p071', + name: 'Onion 1kg', + barcode: '8901234500721', + sku: 'VEG-ONI-1000', + category: ProductCategory.vegetables, + price: 35, + stock: 65, + emoji: '🧅', + unit: UnitOfMeasure.kilogram, + gstRate: 0, + ), + Product( + id: 'p072', + name: 'Potato 1kg', + barcode: '8901234500738', + sku: 'VEG-POT-1000', + category: ProductCategory.vegetables, + price: 30, + stock: 70, + emoji: '🥔', + unit: UnitOfMeasure.kilogram, + gstRate: 0, + ), + Product( + id: 'p073', + name: 'Carrot 500g', + barcode: '8901234500745', + sku: 'VEG-CAR-0500', + category: ProductCategory.vegetables, + price: 32, + stock: 8, + emoji: '🥕', + gstRate: 0, + ), + ]; + + static List customers() => [ + Customer( + id: 'c001', + name: 'Abhishek', + mobile: '9876543210', + email: 'abhishek@example.com', + gender: Gender.male, + dateOfBirth: DateTime(1994, 3, 18), + loyaltyPoints: 320, + lifetimeSpend: 24500, + visitCount: 41, + createdAt: DateTime(2024, 1, 12), + lastVisitAt: DateTime.now().subtract(const Duration(days: 3)), + ), + Customer( + id: 'c002', + name: 'Priya Raman', + mobile: '9812345678', + email: 'priya.r@example.com', + gender: Gender.female, + dateOfBirth: DateTime(1990, 7, 2), + loyaltyPoints: 1180, + lifetimeSpend: 68200, + visitCount: 96, + createdAt: DateTime(2023, 6, 4), + lastVisitAt: DateTime.now().subtract(const Duration(days: 1)), + ), + Customer( + id: 'c003', + name: 'Karthik S', + mobile: '9900112233', + gender: Gender.male, + loyaltyPoints: 45, + lifetimeSpend: 3200, + visitCount: 7, + createdAt: DateTime(2025, 2, 20), + lastVisitAt: DateTime.now().subtract(const Duration(days: 11)), + ), + Customer( + id: 'c004', + name: 'Meena Lakshmi', + mobile: '9445566778', + email: 'meena.l@example.com', + gender: Gender.female, + dateOfBirth: DateTime(1986, 11, 30), + loyaltyPoints: 2640, + lifetimeSpend: 172000, + visitCount: 210, + createdAt: DateTime(2022, 9, 15), + lastVisitAt: DateTime.now().subtract(const Duration(hours: 20)), + ), + ]; +} diff --git a/lib/data/repositories/customer_repository_impl.dart b/lib/data/repositories/customer_repository_impl.dart new file mode 100644 index 0000000..83d543b --- /dev/null +++ b/lib/data/repositories/customer_repository_impl.dart @@ -0,0 +1,96 @@ +import 'package:uuid/uuid.dart'; + +import '../../core/utils/extensions.dart'; +import '../../domain/entities/customer.dart'; +import '../../domain/repositories/customer_repository.dart'; +import '../datasources/local_store.dart'; + +class CustomerRepositoryImpl implements CustomerRepository { + CustomerRepositoryImpl(this._store); + + final LocalStore _store; + static const _uuid = Uuid(); + + String _digits(String v) => v.replaceAll(RegExp(r'\D'), ''); + + @override + Future findByMobile(String mobile) async { + final needle = _digits(mobile); + return _store.customers + .firstWhereOrNull((c) => _digits(c.mobile) == needle); + } + + @override + Future findById(String id) async => _store.customerById(id); + + @override + Future create(Customer customer) async { + final existing = await findByMobile(customer.mobile); + if (existing != null) { + throw StateError('A customer with this mobile number already exists.'); + } + final created = Customer( + id: _uuid.v4(), + name: customer.name.trim(), + mobile: _digits(customer.mobile), + email: customer.email?.trim().isEmpty ?? true + ? null + : customer.email!.trim(), + gender: customer.gender, + dateOfBirth: customer.dateOfBirth, + loyaltyPoints: 0, + lifetimeSpend: 0, + visitCount: 0, + createdAt: DateTime.now(), + ); + _store.putCustomer(created); + return created; + } + + @override + Future update(Customer customer) async { + _store.putCustomer(customer); + return customer; + } + + @override + Future recordSale({ + required String customerId, + required double amount, + required int pointsEarned, + required int pointsRedeemed, + }) async { + final current = _store.customerById(customerId); + if (current == null) { + throw StateError('Customer $customerId not found.'); + } + final updated = current.copyWith( + loyaltyPoints: + (current.loyaltyPoints - pointsRedeemed + pointsEarned) + .clamp(0, 1 << 31), + lifetimeSpend: (current.lifetimeSpend + amount).asMoney, + visitCount: current.visitCount + 1, + lastVisitAt: DateTime.now(), + ); + _store.putCustomer(updated); + return updated; + } + + @override + Future> search(String query) async { + final q = query.trim().toLowerCase(); + if (q.isEmpty) return recent(); + return _store.customers + .where((c) => + c.name.toLowerCase().contains(q) || _digits(c.mobile).contains(q)) + .toList(); + } + + @override + Future> recent({int limit = 20}) async { + final list = _store.customers.toList() + ..sort((a, b) => (b.lastVisitAt ?? DateTime(2000)) + .compareTo(a.lastVisitAt ?? DateTime(2000))); + return list.take(limit).toList(); + } +} diff --git a/lib/data/repositories/product_repository_impl.dart b/lib/data/repositories/product_repository_impl.dart new file mode 100644 index 0000000..442aca0 --- /dev/null +++ b/lib/data/repositories/product_repository_impl.dart @@ -0,0 +1,68 @@ +import '../../core/utils/extensions.dart'; +import '../../domain/entities/product.dart'; +import '../../domain/repositories/product_repository.dart'; +import '../datasources/local_store.dart'; + +class ProductRepositoryImpl implements ProductRepository { + ProductRepositoryImpl(this._store); + + final LocalStore _store; + + @override + Future> getAll() async => + _store.products.where((p) => p.isActive).toList(); + + @override + Future> getByCategory(ProductCategory category) async => + _store.products + .where((p) => p.isActive && p.category == category) + .toList(); + + @override + Future findByBarcode(String barcode) async { + final needle = barcode.trim(); + return _store.products.firstWhereOrNull( + (p) => p.barcode == needle && p.isActive, + ); + } + + @override + Future findById(String id) async => _store.productById(id); + + @override + Future> search(String query) async { + final q = query.trim(); + if (q.isEmpty) return getAll(); + + final results = _store.products.where((p) => p.isActive && p.matches(q)); + + // Rank exact barcode and SKU hits above fuzzy name matches so the top + // result is the one the cashier almost certainly meant. + final ranked = results.toList() + ..sort((a, b) => _score(b, q).compareTo(_score(a, q))); + return ranked; + } + + int _score(Product p, String q) { + final lq = q.toLowerCase(); + if (p.barcode == q) return 100; + if (p.sku.toLowerCase() == lq) return 90; + if (p.name.toLowerCase().startsWith(lq)) return 70; + if (p.name.toLowerCase().contains(lq)) return 50; + if (p.brand?.toLowerCase().contains(lq) ?? false) return 30; + return 10; + } + + @override + Future decrementStock(Map quantities) async { + quantities.forEach((id, qty) { + final p = _store.productById(id); + if (p == null) return; + final next = (p.stock - qty).clamp(0, double.infinity).toDouble(); + _store.putProduct(p.copyWith(stock: next)); + }); + } + + @override + Future upsert(Product product) async => _store.putProduct(product); +} diff --git a/lib/data/repositories/sync_repository_impl.dart b/lib/data/repositories/sync_repository_impl.dart new file mode 100644 index 0000000..6f16c1b --- /dev/null +++ b/lib/data/repositories/sync_repository_impl.dart @@ -0,0 +1,159 @@ +import 'package:uuid/uuid.dart'; + +import '../../core/utils/formatters.dart'; +import '../../domain/entities/shift_report.dart'; +import '../../domain/entities/sync_event.dart'; +import '../../domain/repositories/sync_repository.dart'; +import '../datasources/local_store.dart'; +import '../datasources/remote_catalogue_source.dart'; + +class SyncRepositoryImpl implements SyncRepository { + SyncRepositoryImpl(this._store, this._catalogue, this._reports); + + final LocalStore _store; + final RemoteCatalogueSource _catalogue; + final RemoteReportSink _reports; + + static const _uuid = Uuid(); + + @override + bool get hasCatalogue => _store.hasCatalogue; + + @override + DateTime? get lastImportAt => _store.lastImportAt; + + @override + String? get catalogueRevision => _store.catalogueRevision; + + @override + List get events => _store.events; + + @override + bool get hasUnsyncedEvents => _store.hasUnsyncedEvents; + + @override + Future importCatalogue({ + void Function(double progress, String stage)? onProgress, + }) async { + final event = SyncEvent( + id: _uuid.v4(), + type: SyncEventType.catalogueImport, + status: SyncStatus.syncing, + createdAt: DateTime.now(), + summary: 'Catalogue import started', + ); + _store.addEvent(event); + + try { + final snapshot = await _catalogue.fetch(onProgress: onProgress); + + _store.importCatalogue( + products: snapshot.products, + customers: snapshot.customers, + revision: snapshot.revision, + at: snapshot.fetchedAt, + ); + + final done = event.copyWith( + status: SyncStatus.synced, + syncedAt: DateTime.now(), + attempts: 1, + ); + final settled = SyncEvent( + id: done.id, + type: done.type, + status: done.status, + createdAt: done.createdAt, + summary: '${snapshot.products.length} products, ' + '${snapshot.customers.length} customers · ${snapshot.revision}', + payload: { + 'products': snapshot.products.length, + 'customers': snapshot.customers.length, + 'revision': snapshot.revision, + }, + syncedAt: done.syncedAt, + attempts: 1, + ); + _store.updateEvent(settled); + return settled; + } catch (e) { + final failed = event.copyWith( + status: SyncStatus.failed, + error: e.toString(), + attempts: 1, + ); + _store.updateEvent(failed); + return failed; + } + } + + @override + ShiftReport buildShiftReport({ + required DateTime businessDate, + required String terminalId, + required String cashierName, + }) { + return ShiftReport.fromTransactions( + transactions: _store.transactions, + businessDate: businessDate, + terminalId: terminalId, + cashierName: cashierName, + ); + } + + @override + Future pushShiftReport(ShiftReport report) async { + // Queued first, so the data is durable before the network is touched. + final queued = SyncEvent( + id: _uuid.v4(), + type: SyncEventType.shiftReport, + status: SyncStatus.pending, + createdAt: DateTime.now(), + summary: '${report.billCount} bills · ' + '${Formatters.money(report.grossSales)} · ' + '${Formatters.date(report.businessDate)}', + payload: report.toPayload(), + ); + _store.addEvent(queued); + + return _attempt(queued); + } + + @override + Future retry(String eventId) async { + final matches = _store.events.where((e) => e.id == eventId).toList(); + if (matches.isEmpty) { + throw StateError('No queued event with id $eventId'); + } + final event = matches.first; + if (event.type == SyncEventType.catalogueImport) { + return importCatalogue(); + } + return _attempt(event); + } + + /// Sends one event, leaving it queued if the push fails. + Future _attempt(SyncEvent event) async { + _store.updateEvent(event.copyWith(status: SyncStatus.syncing)); + + try { + await _reports.push(event.payload); + final done = event.copyWith( + status: SyncStatus.synced, + syncedAt: DateTime.now(), + attempts: event.attempts + 1, + clearError: true, + ); + _store.updateEvent(done); + return done.copyWith(); + } catch (e) { + final failed = event.copyWith( + status: SyncStatus.failed, + error: e.toString(), + attempts: event.attempts + 1, + ); + _store.updateEvent(failed); + return failed; + } + } +} diff --git a/lib/data/repositories/transaction_repository_impl.dart b/lib/data/repositories/transaction_repository_impl.dart new file mode 100644 index 0000000..e23584b --- /dev/null +++ b/lib/data/repositories/transaction_repository_impl.dart @@ -0,0 +1,49 @@ +import '../../core/utils/extensions.dart'; +import '../../domain/entities/transaction.dart'; +import '../../domain/repositories/transaction_repository.dart'; +import '../datasources/local_store.dart'; + +class TransactionRepositoryImpl implements TransactionRepository { + TransactionRepositoryImpl(this._store); + + final LocalStore _store; + + @override + Future save(SaleTransaction transaction) async { + _store.addTransaction(transaction); + return transaction; + } + + @override + Future> history({int limit = 50}) async => + _store.transactions.take(limit).toList(); + + @override + Future findByInvoice(String invoiceNumber) async => + _store.transactions + .firstWhereOrNull((t) => t.invoiceNumber == invoiceNumber); + + @override + Future nextInvoiceSequence() async => _store.nextInvoiceSequence(); + + @override + Future park(ParkedBill bill) async => _store.addParked(bill); + + @override + Future> parkedBills() async => _store.parked; + + @override + Future removeParked(String id) async => _store.removeParked(id); + + @override + Future salesTotalForDay(DateTime day) async { + return _store.transactions + .where((t) => + t.status == TransactionStatus.completed && + t.createdAt.year == day.year && + t.createdAt.month == day.month && + t.createdAt.day == day.day) + .fold(0.0, (sum, t) => sum + t.total) + .asMoney; + } +} diff --git a/lib/domain/entities/cart.dart b/lib/domain/entities/cart.dart new file mode 100644 index 0000000..7155b36 --- /dev/null +++ b/lib/domain/entities/cart.dart @@ -0,0 +1,238 @@ +import 'package:equatable/equatable.dart'; + +import '../../core/constants/app_constants.dart'; +import '../../core/utils/extensions.dart'; +import 'customer.dart'; +import 'product.dart'; + +/// How a discount value should be interpreted. +enum DiscountType { none, percentage, flat } + +/// A discount applied to a single line or to the whole bill. +class Discount extends Equatable { + const Discount({this.type = DiscountType.none, this.value = 0, this.reason}); + + final DiscountType type; + final double value; + final String? reason; + + static const Discount none = Discount(); + + bool get isActive => type != DiscountType.none && value > 0; + + /// Resolves the discount to rupees against [base], never exceeding it. + double amountOn(double base) { + if (!isActive || base <= 0) return 0; + final raw = switch (type) { + DiscountType.percentage => base * (value / 100), + DiscountType.flat => value, + DiscountType.none => 0.0, + }; + return raw.clamp(0, base).toDouble().asMoney; + } + + String get label => switch (type) { + DiscountType.percentage => '${value.toStringAsFixed(0)}% off', + DiscountType.flat => 'Flat ${AppConstants.currencySymbol}$value off', + DiscountType.none => 'No discount', + }; + + @override + List get props => [type, value, reason]; +} + +/// One product line inside the cart. +class CartLine extends Equatable { + const CartLine({ + required this.product, + required this.quantity, + this.discount = Discount.none, + this.addedAt, + }); + + final Product product; + final double quantity; + final Discount discount; + final DateTime? addedAt; + + String get id => product.id; + + /// Line value before discount, GST inclusive. + double get grossAmount => (product.price * quantity).asMoney; + + double get discountAmount => discount.amountOn(grossAmount); + + /// Payable for this line after discount, GST inclusive. + double get payable => (grossAmount - discountAmount).asMoney; + + /// Taxable value inside [payable]. + double get taxableValue => (payable / (1 + product.gstRate)).asMoney; + + /// GST rupees inside [payable]. + double get taxAmount => (payable - taxableValue).asMoney; + + double get cgst => (taxAmount / 2).asMoney; + double get sgst => (taxAmount / 2).asMoney; + + double get mrpSavings => product.hasDiscount + ? (product.savings * quantity).asMoney + : 0; + + bool get exceedsStock => quantity > product.stock; + + CartLine copyWith({double? quantity, Discount? discount}) => CartLine( + product: product, + quantity: quantity ?? this.quantity, + discount: discount ?? this.discount, + addedAt: addedAt, + ); + + @override + List get props => [product.id, quantity, discount]; +} + +/// The live bill. Immutable — every mutation returns a new instance, which +/// keeps the Riverpod notifier predictable and makes undo trivial. +class Cart extends Equatable { + const Cart({ + this.lines = const [], + this.customer, + this.billDiscount = Discount.none, + this.pointsRedeemed = 0, + this.note, + }); + + final List lines; + final Customer? customer; + final Discount billDiscount; + final int pointsRedeemed; + final String? note; + + static const Cart empty = Cart(); + + bool get isEmpty => lines.isEmpty; + bool get isNotEmpty => lines.isNotEmpty; + bool get isWalkIn => customer == null; + + int get lineCount => lines.length; + + double get totalQuantity => + lines.fold(0.0, (sum, l) => sum + l.quantity); + + /// Sum of line values before any bill-level discount, GST inclusive. + double get subtotal => + lines.fold(0.0, (sum, l) => sum + l.payable).asMoney; + + /// Discounts applied at the individual line level. + double get lineDiscountTotal => + lines.fold(0.0, (sum, l) => sum + l.discountAmount).asMoney; + + /// Automatic discount earned through the customer's membership tier. + Discount get membershipDiscount { + final rate = customer?.tier.discountRate ?? 0; + if (rate <= 0) return Discount.none; + return Discount( + type: DiscountType.percentage, + value: rate * 100, + reason: '${customer!.tier.label} member', + ); + } + + double get membershipDiscountAmount => + membershipDiscount.amountOn(subtotal); + + double get manualBillDiscountAmount => billDiscount.amountOn(subtotal); + + /// All bill-level reductions combined. + double get billDiscountTotal => + (membershipDiscountAmount + manualBillDiscountAmount) + .clamp(0, subtotal) + .toDouble() + .asMoney; + + double get loyaltyRedemptionValue => + (pointsRedeemed * AppConstants.loyaltyPointValue).asMoney; + + /// Payable after every discount, GST inclusive, before round-off. + double get netAmount { + final v = subtotal - billDiscountTotal - loyaltyRedemptionValue; + return v.clamp(0, double.infinity).toDouble().asMoney; + } + + /// Proportion of the bill remaining after bill-level reductions. Used to + /// spread those reductions fairly across lines when apportioning GST. + double get _billFactor => subtotal <= 0 ? 1 : netAmount / subtotal; + + /// GST payable across the bill, after apportioning bill-level discounts. + double get taxAmount => + lines.fold(0.0, (sum, l) => sum + l.taxAmount * _billFactor).asMoney; + + double get cgst => (taxAmount / 2).asMoney; + double get sgst => (taxAmount / 2).asMoney; + + /// Taxable value across the bill. + double get taxableAmount => (netAmount - taxAmount).asMoney; + + /// GST broken out per slab — required on a compliant tax invoice. + Map get taxBreakdown { + final map = {}; + for (final line in lines) { + final rate = line.product.gstRate; + map[rate] = ((map[rate] ?? 0) + line.taxAmount * _billFactor).asMoney; + } + return map; + } + + double get grandTotal => netAmount.roundedToRupee; + + /// The paise adjustment shown as "Round Off" on the bill. + double get roundOff => (grandTotal - netAmount).asMoney; + + double get mrpSavingsTotal => + lines.fold(0.0, (sum, l) => sum + l.mrpSavings).asMoney; + + /// Everything the shopper saved on this bill. + double get totalSavings => + (mrpSavingsTotal + lineDiscountTotal + billDiscountTotal).asMoney; + + /// Points this sale will earn. Walk-in customers earn nothing. + int get pointsEarned { + if (customer == null) return 0; + return (grandTotal / AppConstants.loyaltyRupeesPerPoint).floor(); + } + + int get maxRedeemablePoints { + final c = customer; + if (c == null) return 0; + final byBalance = c.loyaltyPoints; + final byBill = + (subtotal - billDiscountTotal) ~/ AppConstants.loyaltyPointValue; + return byBalance < byBill ? byBalance : byBill; + } + + CartLine? lineFor(String productId) => + lines.firstWhereOrNull((l) => l.product.id == productId); + + bool contains(String productId) => lineFor(productId) != null; + + Cart copyWith({ + List? lines, + Customer? customer, + bool clearCustomer = false, + Discount? billDiscount, + int? pointsRedeemed, + String? note, + }) { + return Cart( + lines: lines ?? this.lines, + customer: clearCustomer ? null : (customer ?? this.customer), + billDiscount: billDiscount ?? this.billDiscount, + pointsRedeemed: pointsRedeemed ?? this.pointsRedeemed, + note: note ?? this.note, + ); + } + + @override + List get props => + [lines, customer, billDiscount, pointsRedeemed, note]; +} diff --git a/lib/domain/entities/customer.dart b/lib/domain/entities/customer.dart new file mode 100644 index 0000000..7fb1f31 --- /dev/null +++ b/lib/domain/entities/customer.dart @@ -0,0 +1,123 @@ +import 'package:equatable/equatable.dart'; + +import '../../core/constants/app_constants.dart'; + +enum Gender { + male('Male'), + female('Female'), + other('Other'), + unspecified('Prefer not to say'); + + const Gender(this.label); + + final String label; +} + +/// Loyalty tier, derived from lifetime spend. +enum MembershipTier { + bronze('Bronze', 0, 0.0), + silver('Silver', 10000, 0.02), + gold('Gold', 50000, 0.05), + platinum('Platinum', 150000, 0.08); + + const MembershipTier(this.label, this.threshold, this.discountRate); + + final String label; + + /// Lifetime spend in rupees required to reach this tier. + final double threshold; + + /// Automatic bill discount granted to members of this tier. + final double discountRate; + + static MembershipTier forSpend(double lifetimeSpend) { + return MembershipTier.values.lastWhere( + (t) => lifetimeSpend >= t.threshold, + orElse: () => MembershipTier.bronze, + ); + } + + MembershipTier? get next { + final i = index; + return i < MembershipTier.values.length - 1 + ? MembershipTier.values[i + 1] + : null; + } +} + +/// A registered shopper. A `null` customer on a sale means walk-in. +class Customer extends Equatable { + const Customer({ + required this.id, + required this.name, + required this.mobile, + this.email, + this.gender = Gender.unspecified, + this.dateOfBirth, + this.loyaltyPoints = 0, + this.lifetimeSpend = 0, + this.visitCount = 0, + this.createdAt, + this.lastVisitAt, + }); + + final String id; + final String name; + final String mobile; + final String? email; + final Gender gender; + final DateTime? dateOfBirth; + final int loyaltyPoints; + final double lifetimeSpend; + final int visitCount; + final DateTime? createdAt; + final DateTime? lastVisitAt; + + MembershipTier get tier => MembershipTier.forSpend(lifetimeSpend); + + /// Cash value of the points currently held. + double get redeemableValue => + loyaltyPoints * AppConstants.loyaltyPointValue; + + /// Rupees of additional spend needed to reach the next tier. + double? get spendToNextTier { + final next = tier.next; + if (next == null) return null; + return (next.threshold - lifetimeSpend).clamp(0, double.infinity); + } + + bool get isBirthdayToday { + final dob = dateOfBirth; + if (dob == null) return false; + final now = DateTime.now(); + return dob.month == now.month && dob.day == now.day; + } + + Customer copyWith({ + String? name, + String? email, + Gender? gender, + DateTime? dateOfBirth, + int? loyaltyPoints, + double? lifetimeSpend, + int? visitCount, + DateTime? lastVisitAt, + }) { + return Customer( + id: id, + name: name ?? this.name, + mobile: mobile, + email: email ?? this.email, + gender: gender ?? this.gender, + dateOfBirth: dateOfBirth ?? this.dateOfBirth, + loyaltyPoints: loyaltyPoints ?? this.loyaltyPoints, + lifetimeSpend: lifetimeSpend ?? this.lifetimeSpend, + visitCount: visitCount ?? this.visitCount, + createdAt: createdAt, + lastVisitAt: lastVisitAt ?? this.lastVisitAt, + ); + } + + @override + List get props => [id, name, mobile, loyaltyPoints, lifetimeSpend]; +} diff --git a/lib/domain/entities/product.dart b/lib/domain/entities/product.dart new file mode 100644 index 0000000..76ca024 --- /dev/null +++ b/lib/domain/entities/product.dart @@ -0,0 +1,134 @@ +import 'package:equatable/equatable.dart'; + +import '../../core/constants/app_constants.dart'; + +/// Merchandise categories shown as filter chips on the POS dashboard. +enum ProductCategory { + dairy('Dairy', '🥛'), + grocery('Grocery', '🛒'), + fruits('Fruits', '🍎'), + vegetables('Vegetables', '🥦'), + beverages('Beverages', '🥤'), + snacks('Snacks', '🍪'), + personalCare('Personal Care', '🧴'), + household('Household', '🏠'); + + const ProductCategory(this.label, this.emoji); + + final String label; + final String emoji; +} + +/// Unit of measure — drives whether fractional quantities are permitted. +enum UnitOfMeasure { + piece('pc'), + kilogram('kg'), + gram('g'), + litre('L'), + millilitre('ml'), + pack('pack'); + + const UnitOfMeasure(this.symbol); + + final String symbol; + + bool get allowsFractional => + this == UnitOfMeasure.kilogram || this == UnitOfMeasure.litre; +} + +/// A sellable item in the catalogue. +class Product extends Equatable { + const Product({ + required this.id, + required this.name, + required this.barcode, + required this.sku, + required this.category, + required this.price, + required this.stock, + this.mrp, + this.emoji = '📦', + this.imageUrl, + this.unit = UnitOfMeasure.piece, + this.gstRate = AppConstants.defaultGstRate, + this.brand, + this.isActive = true, + }); + + final String id; + final String name; + final String barcode; + final String sku; + final ProductCategory category; + + /// Selling price per [unit], inclusive of GST (Indian retail convention). + final double price; + + /// Printed maximum retail price, used to display savings. + final double? mrp; + + final double stock; + final String emoji; + final String? imageUrl; + final UnitOfMeasure unit; + final double gstRate; + final String? brand; + final bool isActive; + + bool get isOutOfStock => stock <= 0; + bool get isLowStock => + stock > 0 && stock <= AppConstants.lowStockThreshold; + + bool get hasDiscount => mrp != null && mrp! > price; + + double get savings => hasDiscount ? (mrp! - price) : 0; + + double get discountPercent => + hasDiscount ? ((mrp! - price) / mrp!) * 100 : 0; + + /// Price stripped of embedded GST — the taxable value. + double get netPrice => price / (1 + gstRate); + + /// GST rupees embedded inside [price]. + double get taxPerUnit => price - netPrice; + + /// Fuzzy match used by the search bar across name, barcode, SKU and brand. + bool matches(String query) { + final q = query.trim().toLowerCase(); + if (q.isEmpty) return true; + return name.toLowerCase().contains(q) || + barcode.toLowerCase().contains(q) || + sku.toLowerCase().contains(q) || + (brand?.toLowerCase().contains(q) ?? false) || + category.label.toLowerCase().contains(q); + } + + Product copyWith({ + String? name, + double? price, + double? mrp, + double? stock, + ProductCategory? category, + bool? isActive, + }) { + return Product( + id: id, + name: name ?? this.name, + barcode: barcode, + sku: sku, + category: category ?? this.category, + price: price ?? this.price, + mrp: mrp ?? this.mrp, + stock: stock ?? this.stock, + emoji: emoji, + imageUrl: imageUrl, + unit: unit, + gstRate: gstRate, + brand: brand, + isActive: isActive ?? this.isActive, + ); + } + + @override + List get props => [id, name, barcode, sku, price, stock, isActive]; +} diff --git a/lib/domain/entities/shift_report.dart b/lib/domain/entities/shift_report.dart new file mode 100644 index 0000000..d5afb0a --- /dev/null +++ b/lib/domain/entities/shift_report.dart @@ -0,0 +1,152 @@ +import 'package:equatable/equatable.dart'; + +import '../../core/utils/extensions.dart'; +import 'transaction.dart'; + +/// Everything the back office needs from a day at this terminal. +/// +/// Computed from the locally stored transactions, so it can be produced with +/// no connection and pushed whenever one is available. +class ShiftReport extends Equatable { + const ShiftReport({ + required this.businessDate, + required this.terminalId, + required this.cashierName, + required this.billCount, + required this.itemCount, + required this.grossSales, + required this.taxCollected, + required this.discountGiven, + required this.roundOff, + required this.paymentBreakdown, + required this.loyaltyPointsIssued, + required this.loyaltyPointsRedeemed, + this.firstBillAt, + this.lastBillAt, + }); + + final DateTime businessDate; + final String terminalId; + final String cashierName; + + final int billCount; + + /// Total units sold across every bill. + final double itemCount; + + final double grossSales; + final double taxCollected; + final double discountGiven; + final double roundOff; + + final Map paymentBreakdown; + + final int loyaltyPointsIssued; + final int loyaltyPointsRedeemed; + + final DateTime? firstBillAt; + final DateTime? lastBillAt; + + /// A zeroed report for a day with no trading. Not a const — [DateTime] + /// cannot appear in a constant expression. + factory ShiftReport.blank({ + required DateTime businessDate, + required String terminalId, + required String cashierName, + }) => + ShiftReport( + businessDate: businessDate, + terminalId: terminalId, + cashierName: cashierName, + billCount: 0, + itemCount: 0, + grossSales: 0, + taxCollected: 0, + discountGiven: 0, + roundOff: 0, + paymentBreakdown: const {}, + loyaltyPointsIssued: 0, + loyaltyPointsRedeemed: 0, + ); + + bool get isEmpty => billCount == 0; + + double get averageBasket => + billCount == 0 ? 0 : (grossSales / billCount).asMoney; + + double get netOfTax => (grossSales - taxCollected).asMoney; + + /// Builds the report from the day's transactions. + factory ShiftReport.fromTransactions({ + required List transactions, + required DateTime businessDate, + required String terminalId, + required String cashierName, + }) { + final completed = transactions + .where((t) => + t.status == TransactionStatus.completed && + t.createdAt.year == businessDate.year && + t.createdAt.month == businessDate.month && + t.createdAt.day == businessDate.day) + .toList() + ..sort((a, b) => a.createdAt.compareTo(b.createdAt)); + + final byMethod = {}; + for (final t in completed) { + for (final p in t.payments) { + byMethod[p.method] = ((byMethod[p.method] ?? 0) + p.amount).asMoney; + } + } + + return ShiftReport( + businessDate: businessDate, + terminalId: terminalId, + cashierName: cashierName, + billCount: completed.length, + itemCount: + completed.fold(0.0, (s, t) => s + t.cart.totalQuantity), + grossSales: completed.fold(0.0, (s, t) => s + t.total).asMoney, + taxCollected: + completed.fold(0.0, (s, t) => s + t.cart.taxAmount).asMoney, + discountGiven: completed + .fold(0.0, + (s, t) => s + t.cart.billDiscountTotal + t.cart.lineDiscountTotal) + .asMoney, + roundOff: completed.fold(0.0, (s, t) => s + t.cart.roundOff).asMoney, + paymentBreakdown: byMethod, + loyaltyPointsIssued: + completed.fold(0, (s, t) => s + t.pointsEarned), + loyaltyPointsRedeemed: + completed.fold(0, (s, t) => s + t.pointsRedeemed), + firstBillAt: completed.isEmpty ? null : completed.first.createdAt, + lastBillAt: completed.isEmpty ? null : completed.last.createdAt, + ); + } + + /// The JSON body that would be sent to the back office. + Map toPayload() => { + 'business_date': businessDate.toIso8601String().substring(0, 10), + 'terminal_id': terminalId, + 'cashier': cashierName, + 'bill_count': billCount, + 'item_count': itemCount, + 'gross_sales': grossSales, + 'net_of_tax': netOfTax, + 'tax_collected': taxCollected, + 'discount_given': discountGiven, + 'round_off': roundOff, + 'average_basket': averageBasket, + 'loyalty_points_issued': loyaltyPointsIssued, + 'loyalty_points_redeemed': loyaltyPointsRedeemed, + 'first_bill_at': firstBillAt?.toIso8601String(), + 'last_bill_at': lastBillAt?.toIso8601String(), + 'payments': { + for (final e in paymentBreakdown.entries) e.key.name: e.value, + }, + }; + + @override + List get props => + [businessDate, terminalId, billCount, grossSales]; +} diff --git a/lib/domain/entities/store_account.dart b/lib/domain/entities/store_account.dart new file mode 100644 index 0000000..4554017 --- /dev/null +++ b/lib/domain/entities/store_account.dart @@ -0,0 +1,63 @@ +import 'package:equatable/equatable.dart'; + +/// What a staff member is allowed to do. +enum StaffRole { + admin('Admin', 'Full access to every module'), + manager('Manager', 'Sales, inventory and reports'), + cashier('Cashier', 'Billing and customers only'); + + const StaffRole(this.label, this.description); + + final String label; + final String description; + + bool get canVoidSale => this != StaffRole.cashier; + bool get canEditPricing => this == StaffRole.admin; + bool get canViewReports => this != StaffRole.cashier; +} + +/// A person who signs in at the terminal. +class StaffUser extends Equatable { + const StaffUser({ + required this.id, + required this.name, + required this.role, + required this.pin, + }); + + final String id; + final String name; + final StaffRole role; + + /// Four-digit quick-unlock code. Never rendered. + final String pin; + + @override + List get props => [id, name, role]; +} + +/// The registered outlet this terminal belongs to. +class StoreAccount extends Equatable { + const StoreAccount({ + required this.id, + required this.name, + required this.email, + required this.address, + required this.gstin, + required this.phone, + required this.staff, + this.plan = 'Business', + }); + + final String id; + final String name; + final String email; + final String address; + final String gstin; + final String phone; + final List staff; + final String plan; + + @override + List get props => [id, email]; +} diff --git a/lib/domain/entities/sync_event.dart b/lib/domain/entities/sync_event.dart new file mode 100644 index 0000000..50bb0bf --- /dev/null +++ b/lib/domain/entities/sync_event.dart @@ -0,0 +1,85 @@ +import 'package:equatable/equatable.dart'; + +/// The two moments this terminal talks to the server. +enum SyncEventType { + catalogueImport('Catalogue Import', 'Pulled products from the server'), + shiftReport('Shift Report', 'Pushed the day\'s takings to the server'); + + const SyncEventType(this.label, this.description); + + final String label; + final String description; + + bool get isInbound => this == SyncEventType.catalogueImport; +} + +enum SyncStatus { + /// Held locally, not yet sent. Nothing is ever discarded in this state. + pending('Pending'), + syncing('Syncing'), + synced('Synced'), + failed('Failed'); + + const SyncStatus(this.label); + + final String label; + + bool get isTerminal => this == SyncStatus.synced; + bool get needsAttention => this == SyncStatus.failed || this == SyncStatus.pending; +} + +/// A durable record of one sync attempt. +/// +/// Events are never deleted on failure — a failed push stays queued so the +/// day's takings survive a dropped connection. +class SyncEvent extends Equatable { + const SyncEvent({ + required this.id, + required this.type, + required this.status, + required this.createdAt, + required this.summary, + this.payload = const {}, + this.syncedAt, + this.error, + this.attempts = 0, + }); + + final String id; + final SyncEventType type; + final SyncStatus status; + final DateTime createdAt; + + /// One-line description shown in the events log. + final String summary; + + /// What would be transmitted. Kept so a retry needs no recomputation. + final Map payload; + + final DateTime? syncedAt; + final String? error; + final int attempts; + + SyncEvent copyWith({ + SyncStatus? status, + DateTime? syncedAt, + String? error, + bool clearError = false, + int? attempts, + }) { + return SyncEvent( + id: id, + type: type, + status: status ?? this.status, + createdAt: createdAt, + summary: summary, + payload: payload, + syncedAt: syncedAt ?? this.syncedAt, + error: clearError ? null : (error ?? this.error), + attempts: attempts ?? this.attempts, + ); + } + + @override + List get props => [id, status, attempts, syncedAt]; +} diff --git a/lib/domain/entities/transaction.dart b/lib/domain/entities/transaction.dart new file mode 100644 index 0000000..03c18c4 --- /dev/null +++ b/lib/domain/entities/transaction.dart @@ -0,0 +1,133 @@ +import 'package:equatable/equatable.dart'; + +import '../../core/utils/extensions.dart'; +import 'cart.dart'; +import 'customer.dart'; + +enum PaymentMethod { + cash('Cash', '💵', true), + card('Card', '💳', false), + upi('UPI', '📱', false), + wallet('Wallet', '👛', false), + giftCard('Gift Card', '🎁', false), + loyalty('Loyalty Points', '⭐', false); + + const PaymentMethod(this.label, this.emoji, this.needsChange); + + final String label; + final String emoji; + + /// Only cash tenders can be over-paid and produce change. + final bool needsChange; + + /// Non-cash tenders normally capture a reference number. + bool get needsReference => + this == PaymentMethod.card || + this == PaymentMethod.upi || + this == PaymentMethod.giftCard; +} + +/// A single tender against a bill. A split payment holds several of these. +class PaymentSplit extends Equatable { + const PaymentSplit({ + required this.method, + required this.amount, + this.tendered, + this.reference, + }); + + final PaymentMethod method; + + /// Amount settled by this tender. + final double amount; + + /// Cash handed over — may exceed [amount]. + final double? tendered; + + /// Card approval code, UPI txn id, gift card number. + final String? reference; + + double get change { + if (!method.needsChange || tendered == null) return 0; + final diff = tendered! - amount; + return diff > 0 ? diff.asMoney : 0; + } + + @override + List get props => [method, amount, tendered, reference]; +} + +enum TransactionStatus { completed, parked, voided, refunded } + +/// An immutable record of a finished sale. +class SaleTransaction extends Equatable { + const SaleTransaction({ + required this.id, + required this.invoiceNumber, + required this.cart, + required this.payments, + required this.createdAt, + required this.cashierName, + this.status = TransactionStatus.completed, + this.terminalId = 'TERM-01', + }); + + final String id; + final String invoiceNumber; + final Cart cart; + final List payments; + final DateTime createdAt; + final String cashierName; + final TransactionStatus status; + final String terminalId; + + Customer? get customer => cart.customer; + + double get total => cart.grandTotal; + + double get amountPaid => + payments.fold(0.0, (sum, p) => sum + p.amount).asMoney; + + double get amountTendered => payments + .fold(0.0, (sum, p) => sum + (p.tendered ?? p.amount)) + .asMoney; + + double get changeDue => + payments.fold(0.0, (sum, p) => sum + p.change).asMoney; + + double get balanceDue => (total - amountPaid).clamp(0, double.infinity); + + bool get isFullySettled => balanceDue <= 0.001; + + bool get isSplit => payments.length > 1; + + int get pointsEarned => cart.pointsEarned; + int get pointsRedeemed => cart.pointsRedeemed; + + String get paymentSummary => + payments.map((p) => p.method.label).toSet().join(' + '); + + @override + List get props => [id, invoiceNumber, createdAt, status]; +} + +/// A bill set aside so the cashier can serve the next shopper. +class ParkedBill extends Equatable { + const ParkedBill({ + required this.id, + required this.cart, + required this.parkedAt, + this.label, + }); + + final String id; + final Cart cart; + final DateTime parkedAt; + final String? label; + + String get displayLabel => + label ?? cart.customer?.name ?? 'Walk-in #${id.substring(0, 4)}'; + + @override + List get props => [id, parkedAt]; +} diff --git a/lib/domain/repositories/customer_repository.dart b/lib/domain/repositories/customer_repository.dart new file mode 100644 index 0000000..ba343a5 --- /dev/null +++ b/lib/domain/repositories/customer_repository.dart @@ -0,0 +1,24 @@ +import '../entities/customer.dart'; + +abstract class CustomerRepository { + /// Primary lookup on the Existing Customer screen. + Future findByMobile(String mobile); + + Future findById(String id); + + Future create(Customer customer); + + Future update(Customer customer); + + /// Applies loyalty and lifetime-spend changes once a sale completes. + Future recordSale({ + required String customerId, + required double amount, + required int pointsEarned, + required int pointsRedeemed, + }); + + Future> search(String query); + + Future> recent({int limit = 20}); +} diff --git a/lib/domain/repositories/product_repository.dart b/lib/domain/repositories/product_repository.dart new file mode 100644 index 0000000..f4de664 --- /dev/null +++ b/lib/domain/repositories/product_repository.dart @@ -0,0 +1,22 @@ +import '../entities/product.dart'; + +/// Contract for catalogue access. Implemented in the data layer so the +/// presentation layer never depends on Hive, HTTP or any other detail. +abstract class ProductRepository { + Future> getAll(); + + Future> getByCategory(ProductCategory category); + + /// Exact barcode lookup — the hot path for scanner billing. + Future findByBarcode(String barcode); + + Future findById(String id); + + /// Fuzzy search across name, barcode, SKU, brand and category. + Future> search(String query); + + /// Decrements stock after a completed sale. + Future decrementStock(Map quantitiesByProductId); + + Future upsert(Product product); +} diff --git a/lib/domain/repositories/sync_repository.dart b/lib/domain/repositories/sync_repository.dart new file mode 100644 index 0000000..799c7ed --- /dev/null +++ b/lib/domain/repositories/sync_repository.dart @@ -0,0 +1,38 @@ +import '../entities/shift_report.dart'; +import '../entities/sync_event.dart'; + +/// The terminal's two network touchpoints, plus the durable event log. +abstract class SyncRepository { + /// True once products have been pulled onto this terminal. + bool get hasCatalogue; + + DateTime? get lastImportAt; + String? get catalogueRevision; + + /// Pulls the catalogue and writes it locally. + /// + /// Records a [SyncEventType.catalogueImport] event whether or not it + /// succeeds, so the log reflects every attempt. + Future importCatalogue({ + void Function(double progress, String stage)? onProgress, + }); + + /// Builds the day's report from locally stored sales. + ShiftReport buildShiftReport({ + required DateTime businessDate, + required String terminalId, + required String cashierName, + }); + + /// Queues the report and attempts to push it. + /// + /// On failure the event is kept in [SyncStatus.failed] so nothing is lost. + Future pushShiftReport(ShiftReport report); + + /// Retries a previously failed or pending push. + Future retry(String eventId); + + List get events; + + bool get hasUnsyncedEvents; +} diff --git a/lib/domain/repositories/transaction_repository.dart b/lib/domain/repositories/transaction_repository.dart new file mode 100644 index 0000000..4fee42d --- /dev/null +++ b/lib/domain/repositories/transaction_repository.dart @@ -0,0 +1,20 @@ +import '../entities/transaction.dart'; + +abstract class TransactionRepository { + Future save(SaleTransaction transaction); + + Future> history({int limit = 50}); + + Future findByInvoice(String invoiceNumber); + + /// Next invoice sequence for the current month. + Future nextInvoiceSequence(); + + Future park(ParkedBill bill); + + Future> parkedBills(); + + Future removeParked(String id); + + Future salesTotalForDay(DateTime day); +} diff --git a/lib/domain/usecases/checkout_sale.dart b/lib/domain/usecases/checkout_sale.dart new file mode 100644 index 0000000..e9746b5 --- /dev/null +++ b/lib/domain/usecases/checkout_sale.dart @@ -0,0 +1,139 @@ +import 'package:uuid/uuid.dart'; + +import '../../core/constants/app_constants.dart'; +import '../../core/utils/formatters.dart'; +import '../entities/cart.dart'; +import '../entities/customer.dart'; +import '../entities/transaction.dart'; +import '../repositories/customer_repository.dart'; +import '../repositories/product_repository.dart'; +import '../repositories/transaction_repository.dart'; + +/// Raised when a sale cannot be completed. Carries a cashier-readable message. +class CheckoutFailure implements Exception { + const CheckoutFailure(this.message); + + final String message; + + @override + String toString() => message; +} + +/// Result of a successful checkout. +class CheckoutResult { + const CheckoutResult({required this.transaction, this.updatedCustomer}); + + final SaleTransaction transaction; + final Customer? updatedCustomer; +} + +/// Completes a sale end to end. +/// +/// Validates tenders, persists the transaction, decrements stock and applies +/// loyalty movement. Everything the cashier's Complete Sale button needs lives +/// here rather than in the UI, so the flow is unit-testable in isolation. +class CheckoutSale { + const CheckoutSale({ + required ProductRepository productRepository, + required CustomerRepository customerRepository, + required TransactionRepository transactionRepository, + }) : _products = productRepository, + _customers = customerRepository, + _transactions = transactionRepository; + + final ProductRepository _products; + final CustomerRepository _customers; + final TransactionRepository _transactions; + + static const _uuid = Uuid(); + + Future call({ + required Cart cart, + required List payments, + required String cashierName, + }) async { + _validate(cart, payments); + + final now = DateTime.now(); + final sequence = await _transactions.nextInvoiceSequence(); + + final transaction = SaleTransaction( + id: _uuid.v4(), + invoiceNumber: Formatters.invoiceNumber(sequence, now), + cart: cart, + payments: payments, + createdAt: now, + cashierName: cashierName, + ); + + await _transactions.save(transaction); + + await _products.decrementStock({ + for (final line in cart.lines) line.product.id: line.quantity, + }); + + Customer? updatedCustomer; + final customer = cart.customer; + if (customer != null) { + updatedCustomer = await _customers.recordSale( + customerId: customer.id, + amount: cart.grandTotal, + pointsEarned: cart.pointsEarned, + pointsRedeemed: cart.pointsRedeemed, + ); + } + + return CheckoutResult( + transaction: transaction, + updatedCustomer: updatedCustomer, + ); + } + + void _validate(Cart cart, List payments) { + if (cart.isEmpty) { + throw const CheckoutFailure('Add at least one item before charging.'); + } + if (payments.isEmpty) { + throw const CheckoutFailure('Select a payment method.'); + } + + for (final line in cart.lines) { + if (line.quantity <= 0) { + throw CheckoutFailure('${line.product.name} has an invalid quantity.'); + } + if (line.exceedsStock) { + throw CheckoutFailure( + 'Only ${line.product.stock.toStringAsFixed(0)} ' + '${line.product.unit.symbol} of ${line.product.name} in stock.', + ); + } + } + + if (cart.pointsRedeemed > 0) { + final available = cart.customer?.loyaltyPoints ?? 0; + if (cart.pointsRedeemed > available) { + throw const CheckoutFailure('Not enough loyalty points to redeem.'); + } + } + + final paid = payments.fold(0.0, (sum, p) => sum + p.amount); + final shortfall = cart.grandTotal - paid; + if (shortfall > 0.01) { + throw CheckoutFailure( + '${AppConstants.currencySymbol}${shortfall.toStringAsFixed(2)} ' + 'still due on this bill.', + ); + } + + for (final p in payments) { + if (p.amount <= 0) { + throw CheckoutFailure('${p.method.label} amount must be positive.'); + } + if (p.method.needsChange && + p.tendered != null && + p.tendered! < p.amount) { + throw const CheckoutFailure('Cash tendered is less than the amount due.'); + } + } + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..9ecd689 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,37 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'app/app.dart'; +import 'core/services/sound_service.dart'; +import 'data/datasources/local_store.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + await _configureChrome(); + + await LocalStore.instance.init(); + await SoundService.instance.preload(); + + runApp(const ProviderScope(child: NearlePosApp())); +} + +/// Locks the terminal into landscape and hides the system bars. +/// +/// Both calls are Android/iOS only. On desktop the window manager owns sizing +/// and chrome, so we skip them — invoking them there is at best a no-op and can +/// raise a MissingPluginException on some engine builds. +Future _configureChrome() async { + final isMobile = defaultTargetPlatform == TargetPlatform.android || + defaultTargetPlatform == TargetPlatform.iOS; + if (kIsWeb || !isMobile) return; + + await SystemChrome.setPreferredOrientations([ + DeviceOrientation.landscapeLeft, + DeviceOrientation.landscapeRight, + ]); + + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky); +} diff --git a/lib/presentation/auth/providers/auth_controller.dart b/lib/presentation/auth/providers/auth_controller.dart new file mode 100644 index 0000000..70a6321 --- /dev/null +++ b/lib/presentation/auth/providers/auth_controller.dart @@ -0,0 +1,115 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/constants/app_constants.dart'; +import '../../../domain/entities/store_account.dart'; + +/// Sign-in state for the terminal. +sealed class AuthState { + const AuthState(); + + bool get isAuthenticated => this is Authenticated; +} + +class Unauthenticated extends AuthState { + const Unauthenticated(); +} + +class Authenticating extends AuthState { + const Authenticating(); +} + +class Authenticated extends AuthState { + const Authenticated({required this.store, required this.user}); + + final StoreAccount store; + final StaffUser user; +} + +class AuthFailure extends AuthState { + const AuthFailure(this.message); + + final String message; +} + +/// Credentials that ship with the demo build. +class DemoCredentials { + const DemoCredentials._(); + + static const String email = 'admin@nearle.in'; + static const String password = 'nearle123'; +} + +const _demoStore = StoreAccount( + id: 'store-001', + name: AppConstants.storeName, + email: DemoCredentials.email, + address: AppConstants.storeAddress, + gstin: AppConstants.storeGstin, + phone: AppConstants.storePhone, + staff: [ + StaffUser(id: 'u1', name: 'Suriya', role: StaffRole.admin, pin: '1234'), + StaffUser(id: 'u2', name: 'Divya', role: StaffRole.manager, pin: '2345'), + StaffUser(id: 'u3', name: 'Rahul', role: StaffRole.cashier, pin: '3456'), + ], +); + +/// Validates store credentials and holds the signed-in session. +/// +/// Backed by a hardcoded account for now; swapping in a real identity provider +/// means changing only [signIn]. +class AuthController extends StateNotifier { + AuthController() : super(const Unauthenticated()); + + Future signIn({ + required String email, + required String password, + }) async { + state = const Authenticating(); + + // Stand-in for the network round trip. + await Future.delayed(const Duration(milliseconds: 600)); + + final normalised = email.trim().toLowerCase(); + + if (normalised != DemoCredentials.email) { + state = const AuthFailure('No store is registered against that email.'); + return false; + } + + if (password != DemoCredentials.password) { + state = const AuthFailure('Incorrect password. Please try again.'); + return false; + } + + state = Authenticated(store: _demoStore, user: _demoStore.staff.first); + return true; + } + + /// Switches the active operator without signing the store out. + void switchUser(StaffUser user) { + final current = state; + if (current is! Authenticated) return; + state = Authenticated(store: current.store, user: user); + } + + void signOut() => state = const Unauthenticated(); + + void clearError() { + if (state is AuthFailure) state = const Unauthenticated(); + } +} + +final authControllerProvider = + StateNotifierProvider((ref) => AuthController()); + +/// The signed-in store, or null before sign-in. +final currentStoreProvider = Provider((ref) { + final s = ref.watch(authControllerProvider); + return s is Authenticated ? s.store : null; +}); + +/// The active operator, or null before sign-in. +final currentUserProvider = Provider((ref) { + final s = ref.watch(authControllerProvider); + return s is Authenticated ? s.user : null; +}); diff --git a/lib/presentation/auth/screens/login_screen.dart b/lib/presentation/auth/screens/login_screen.dart new file mode 100644 index 0000000..6a68ac1 --- /dev/null +++ b/lib/presentation/auth/screens/login_screen.dart @@ -0,0 +1,549 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_animate/flutter_animate.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../app/providers.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/validators.dart'; +import '../../../core/widgets/primary_button.dart'; +import '../providers/auth_controller.dart'; + +/// Store sign-in. The terminal shows this until a valid account is entered. +class LoginScreen extends ConsumerStatefulWidget { + const LoginScreen({super.key}); + + @override + ConsumerState createState() => _LoginScreenState(); +} + +class _LoginScreenState extends ConsumerState { + final _formKey = GlobalKey(); + final _email = TextEditingController(text: DemoCredentials.email); + final _password = TextEditingController(text: DemoCredentials.password); + + bool _obscure = true; + bool _rememberTerminal = true; + + @override + void dispose() { + _email.dispose(); + _password.dispose(); + super.dispose(); + } + + Future _submit() async { + FocusScope.of(context).unfocus(); + if (!(_formKey.currentState?.validate() ?? false)) return; + + final ok = await ref.read(authControllerProvider.notifier).signIn( + email: _email.text, + password: _password.text, + ); + + if (ok && mounted) context.go(AppRoutes.welcome); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.background, + body: LayoutBuilder( + builder: (context, constraints) { + // Below this there isn't room for the brand panel beside the form. + final showBrandPanel = constraints.maxWidth >= 1000; + + return Row( + children: [ + if (showBrandPanel) + const Expanded(flex: 5, child: _BrandPanel()), + Expanded( + flex: 4, + child: _FormPanel( + formKey: _formKey, + email: _email, + password: _password, + obscure: _obscure, + rememberTerminal: _rememberTerminal, + showCompactLogo: !showBrandPanel, + onToggleObscure: () => setState(() => _obscure = !_obscure), + onToggleRemember: (v) => + setState(() => _rememberTerminal = v ?? true), + onSubmit: _submit, + ), + ), + ], + ); + }, + ), + ); + } +} + +class _BrandPanel extends StatelessWidget { + const _BrandPanel(); + + @override + Widget build(BuildContext context) { + return Container( + decoration: const BoxDecoration(gradient: AppColors.primaryGradient), + child: SafeArea( + child: Padding( + padding: const EdgeInsets.all(AppSpacing.giant), + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 42, + height: 42, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(11), + ), + alignment: Alignment.center, + child: const Text( + 'N', + style: TextStyle( + color: AppColors.primary, + fontSize: 23, + fontWeight: FontWeight.w800, + ), + ), + ), + const SizedBox(width: AppSpacing.md), + const Flexible( + child: Text( + 'Nearle POS', + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: Colors.white, + fontSize: 22, + fontWeight: FontWeight.w700, + letterSpacing: -0.4, + ), + ), + ), + ], + ), + const SizedBox(height: AppSpacing.giant), + const Text( + 'Billing that keeps up\nwith your counter.', + style: TextStyle( + color: Colors.white, + fontSize: 34, + height: 1.25, + fontWeight: FontWeight.w700, + letterSpacing: -1, + ), + ), + const SizedBox(height: AppSpacing.lg), + Text( + 'Scanner-first billing, GST-ready invoices and loyalty ' + 'built in — for supermarkets, pharmacies and retail.', + style: TextStyle( + color: Colors.white.withValues(alpha: 0.78), + fontSize: 15, + height: 1.6, + ), + ), + const SizedBox(height: AppSpacing.giant), + const _Feature( + icon: Icons.qr_code_scanner_rounded, + title: 'Scan and go', + body: 'No dialogs between items. Barcode to bill instantly.', + ), + const _Feature( + icon: Icons.receipt_long_rounded, + title: 'GST compliant', + body: 'Per-slab tax split into CGST and SGST on every bill.', + ), + const _Feature( + icon: Icons.stars_rounded, + title: 'Loyalty that runs itself', + body: 'Tiers and points applied without cashier input.', + ), + ], + ), + ), + ), + ), + ).animate().fadeIn(duration: 300.ms); + } +} + +class _Feature extends StatelessWidget { + const _Feature({ + required this.icon, + required this.title, + required this.body, + }); + + final IconData icon; + final String title; + final String body; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: AppSpacing.xl), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 38, + height: 38, + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.16), + borderRadius: AppRadius.brSm, + ), + child: Icon(icon, color: Colors.white, size: 19), + ), + const SizedBox(width: AppSpacing.lg), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + color: Colors.white, + fontSize: 15, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 2), + Text( + body, + style: TextStyle( + color: Colors.white.withValues(alpha: 0.72), + fontSize: 13, + height: 1.5, + ), + ), + ], + ), + ), + ], + ), + ); + } +} + +class _FormPanel extends ConsumerWidget { + const _FormPanel({ + required this.formKey, + required this.email, + required this.password, + required this.obscure, + required this.rememberTerminal, + required this.showCompactLogo, + required this.onToggleObscure, + required this.onToggleRemember, + required this.onSubmit, + }); + + final GlobalKey formKey; + final TextEditingController email; + final TextEditingController password; + final bool obscure; + final bool rememberTerminal; + final bool showCompactLogo; + final VoidCallback onToggleObscure; + final ValueChanged onToggleRemember; + final VoidCallback onSubmit; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final auth = ref.watch(authControllerProvider); + final session = ref.watch(cashierSessionProvider); + final busy = auth is Authenticating; + + return SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(AppSpacing.xxl), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Form( + key: formKey, + autovalidateMode: AutovalidateMode.onUserInteraction, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + if (showCompactLogo) ...[ + Center( + child: Container( + width: 52, + height: 52, + decoration: BoxDecoration( + gradient: AppColors.primaryGradient, + borderRadius: BorderRadius.circular(14), + ), + alignment: Alignment.center, + child: const Text( + 'N', + style: TextStyle( + color: Colors.white, + fontSize: 26, + fontWeight: FontWeight.w800, + ), + ), + ), + ), + const SizedBox(height: AppSpacing.xxl), + ], + + Text( + 'Sign in to your store', + style: Theme.of(context).textTheme.headlineSmall, + ), + const SizedBox(height: AppSpacing.xs), + const Text( + 'Use the credentials issued when your outlet was ' + 'registered.', + style: TextStyle( + fontSize: 13.5, + color: AppColors.textSecondary, + height: 1.5, + ), + ), + const SizedBox(height: AppSpacing.xxxl), + + const _Label('Store email'), + TextFormField( + controller: email, + keyboardType: TextInputType.emailAddress, + textInputAction: TextInputAction.next, + enabled: !busy, + validator: (v) => (v ?? '').trim().isEmpty + ? 'Store email is required' + : Validators.emailOptional(v), + decoration: const InputDecoration( + hintText: 'store@example.in', + prefixIcon: Icon(Icons.storefront_outlined), + ), + ), + const SizedBox(height: AppSpacing.lg), + + const _Label('Password'), + TextFormField( + controller: password, + obscureText: obscure, + enabled: !busy, + textInputAction: TextInputAction.done, + onFieldSubmitted: (_) => onSubmit(), + validator: (v) => (v ?? '').isEmpty + ? 'Password is required' + : ((v ?? '').length < 6 + ? 'Password looks too short' + : null), + decoration: InputDecoration( + hintText: 'Enter your password', + prefixIcon: const Icon(Icons.lock_outline_rounded), + suffixIcon: IconButton( + onPressed: onToggleObscure, + icon: Icon( + obscure + ? Icons.visibility_outlined + : Icons.visibility_off_outlined, + size: 20, + ), + tooltip: obscure ? 'Show password' : 'Hide password', + ), + ), + ), + const SizedBox(height: AppSpacing.sm), + + // Wrap, not Row — on a narrow tablet these would collide. + Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + InkWell( + onTap: busy + ? null + : () => onToggleRemember(!rememberTerminal), + borderRadius: AppRadius.brXs, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: 22, + height: 22, + child: Checkbox( + value: rememberTerminal, + onChanged: busy ? null : onToggleRemember, + visualDensity: VisualDensity.compact, + ), + ), + const SizedBox(width: AppSpacing.sm), + const Text( + 'Remember this terminal', + style: TextStyle( + fontSize: 13, + color: AppColors.textSecondary, + ), + ), + ], + ), + ), + ), + TextButton( + onPressed: busy ? null : () {}, + child: const Text('Forgot password?'), + ), + ], + ), + + if (auth is AuthFailure) ...[ + const SizedBox(height: AppSpacing.sm), + Container( + padding: const EdgeInsets.all(AppSpacing.md), + decoration: BoxDecoration( + color: AppColors.dangerSurface, + borderRadius: AppRadius.brSm, + ), + child: Row( + children: [ + const Icon(Icons.error_outline_rounded, + color: AppColors.danger, size: 18), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Text( + auth.message, + style: const TextStyle( + color: AppColors.danger, + fontSize: 13, + ), + ), + ), + ], + ), + ).animate().shake(duration: 320.ms, hz: 3), + ], + + const SizedBox(height: AppSpacing.xl), + PrimaryButton( + label: 'Sign in', + icon: Icons.login_rounded, + large: true, + busy: busy, + onPressed: onSubmit, + ), + + const SizedBox(height: AppSpacing.xl), + _DemoHint( + onFill: busy + ? null + : () { + email.text = DemoCredentials.email; + password.text = DemoCredentials.password; + }, + ), + + const SizedBox(height: AppSpacing.xxl), + Center( + child: Text( + 'Terminal ${session.terminalId}', + style: const TextStyle( + fontSize: 11.5, + color: AppColors.textTertiary, + ), + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} + +class _Label extends StatelessWidget { + const _Label(this.text); + + final String text; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: AppSpacing.sm), + child: Text( + text, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: AppColors.textSecondary, + ), + ), + ); + } +} + +class _DemoHint extends StatelessWidget { + const _DemoHint({this.onFill}); + + final VoidCallback? onFill; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(AppSpacing.md), + decoration: BoxDecoration( + color: AppColors.primarySurface, + borderRadius: AppRadius.brSm, + border: Border.all(color: AppColors.primaryBorder), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon(Icons.info_outline_rounded, + size: 17, color: AppColors.primary), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Demo account', + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: AppColors.primary, + ), + ), + const SizedBox(height: 2), + SelectableText( + '${DemoCredentials.email} · ${DemoCredentials.password}', + style: const TextStyle( + fontSize: 12, + color: AppColors.textSecondary, + ), + ), + ], + ), + ), + TextButton( + onPressed: onFill, + style: TextButton.styleFrom( + minimumSize: const Size(0, 32), + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.sm), + ), + child: const Text('Fill', style: TextStyle(fontSize: 12.5)), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/customer/providers/customer_providers.dart b/lib/presentation/customer/providers/customer_providers.dart new file mode 100644 index 0000000..19ce173 --- /dev/null +++ b/lib/presentation/customer/providers/customer_providers.dart @@ -0,0 +1,71 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../app/providers.dart'; +import '../../../domain/entities/customer.dart'; + +/// Outcome of the mobile-number lookup on the Existing Customer screen. +sealed class CustomerLookupState { + const CustomerLookupState(); +} + +class LookupIdle extends CustomerLookupState { + const LookupIdle(); +} + +class LookupSearching extends CustomerLookupState { + const LookupSearching(); +} + +class LookupFound extends CustomerLookupState { + const LookupFound(this.customer); + + final Customer customer; +} + +class LookupNotFound extends CustomerLookupState { + const LookupNotFound(this.mobile); + + final String mobile; +} + +class LookupError extends CustomerLookupState { + const LookupError(this.message); + + final String message; +} + +class CustomerLookupController extends StateNotifier { + CustomerLookupController(this._ref) : super(const LookupIdle()); + + final Ref _ref; + + Future search(String mobile) async { + final digits = mobile.replaceAll(RegExp(r'\D'), ''); + if (digits.length != 10) { + state = const LookupIdle(); + return; + } + + state = const LookupSearching(); + try { + final customer = + await _ref.read(customerRepositoryProvider).findByMobile(digits); + state = customer != null + ? LookupFound(customer) + : LookupNotFound(digits); + } catch (e) { + state = LookupError(e.toString()); + } + } + + void reset() => state = const LookupIdle(); +} + +final customerLookupProvider = + StateNotifierProvider( + (ref) => CustomerLookupController(ref), +); + +final recentCustomersProvider = FutureProvider>( + (ref) => ref.watch(customerRepositoryProvider).recent(limit: 6), +); diff --git a/lib/presentation/customer/screens/customer_registration_screen.dart b/lib/presentation/customer/screens/customer_registration_screen.dart new file mode 100644 index 0000000..c7785bd --- /dev/null +++ b/lib/presentation/customer/screens/customer_registration_screen.dart @@ -0,0 +1,321 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../app/providers.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/extensions.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/utils/validators.dart'; +import '../../../core/widgets/glass_card.dart'; +import '../../../core/widgets/primary_button.dart'; +import '../../../domain/entities/customer.dart'; +import '../../pos/providers/cart_controller.dart'; +import '../providers/customer_providers.dart'; + +/// Screen 2 — registers a shopper and drops straight into billing. +class CustomerRegistrationScreen extends ConsumerStatefulWidget { + const CustomerRegistrationScreen({super.key, this.prefillMobile}); + + final String? prefillMobile; + + @override + ConsumerState createState() => + _CustomerRegistrationScreenState(); +} + +class _CustomerRegistrationScreenState + extends ConsumerState { + final _formKey = GlobalKey(); + late final TextEditingController _mobile; + final _name = TextEditingController(); + final _email = TextEditingController(); + + Gender _gender = Gender.unspecified; + DateTime? _dob; + bool _saving = false; + String? _serverError; + + @override + void initState() { + super.initState(); + _mobile = TextEditingController(text: widget.prefillMobile ?? ''); + } + + @override + void dispose() { + _mobile.dispose(); + _name.dispose(); + _email.dispose(); + super.dispose(); + } + + Future _save() async { + setState(() => _serverError = null); + if (!(_formKey.currentState?.validate() ?? false)) return; + + setState(() => _saving = true); + try { + final customer = await ref.read(customerRepositoryProvider).create( + Customer( + id: '', + name: _name.text, + mobile: _mobile.text, + email: _email.text, + gender: _gender, + dateOfBirth: _dob, + ), + ); + + ref.read(cartControllerProvider.notifier).attachCustomer(customer); + ref.invalidate(recentCustomersProvider); + + if (!mounted) return; + context.go(AppRoutes.pos); + } catch (e) { + if (!mounted) return; + setState(() { + _saving = false; + _serverError = e is StateError ? e.message : 'Could not save customer.'; + }); + } + } + + Future _pickDob() async { + final now = DateTime.now(); + final picked = await showDatePicker( + context: context, + initialDate: _dob ?? DateTime(now.year - 25), + firstDate: DateTime(now.year - 100), + lastDate: now, + helpText: 'Date of birth', + ); + if (picked != null) setState(() => _dob = picked); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.background, + appBar: AppBar( + title: const Text('New Customer'), + leading: IconButton( + icon: const Icon(Icons.arrow_back_rounded), + onPressed: () => context.pop(), + ), + ), + body: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(AppSpacing.xxl), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 640), + child: GlassCard( + padding: const EdgeInsets.all(AppSpacing.xxxl), + radius: AppRadius.xl, + shadows: AppColors.shadowMd, + child: Form( + key: _formKey, + autovalidateMode: AutovalidateMode.onUserInteraction, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Register a shopper', + style: context.text.headlineSmall), + const SizedBox(height: AppSpacing.xs), + Text( + 'Only the mobile number and name are required.', + style: context.text.bodySmall, + ), + const SizedBox(height: AppSpacing.xxl), + + _Field( + label: 'Mobile Number', + required: true, + child: TextFormField( + controller: _mobile, + autofocus: true, + keyboardType: TextInputType.phone, + maxLength: 10, + validator: Validators.mobile, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + ], + decoration: const InputDecoration( + hintText: '10-digit mobile number', + prefixText: '+91 ', + counterText: '', + prefixIcon: Icon(Icons.phone_outlined), + ), + ), + ), + + _Field( + label: 'Customer Name', + required: true, + child: TextFormField( + controller: _name, + textCapitalization: TextCapitalization.words, + validator: Validators.name, + decoration: const InputDecoration( + hintText: 'Full name', + prefixIcon: Icon(Icons.person_outline_rounded), + ), + ), + ), + + _Field( + label: 'Email', + child: TextFormField( + controller: _email, + keyboardType: TextInputType.emailAddress, + validator: Validators.emailOptional, + decoration: const InputDecoration( + hintText: 'name@example.com', + prefixIcon: Icon(Icons.mail_outline_rounded), + ), + ), + ), + + _Field( + label: 'Gender', + child: Wrap( + spacing: AppSpacing.sm, + children: Gender.values + .map((g) => ChoiceChip( + label: Text(g.label), + selected: _gender == g, + onSelected: (_) => + setState(() => _gender = g), + labelStyle: TextStyle( + color: _gender == g + ? Colors.white + : AppColors.textSecondary, + fontWeight: FontWeight.w600, + ), + )) + .toList(), + ), + ), + + _Field( + label: 'Date of Birth', + child: InkWell( + onTap: _pickDob, + borderRadius: AppRadius.brMd, + child: InputDecorator( + decoration: const InputDecoration( + prefixIcon: Icon(Icons.cake_outlined), + ), + child: Text( + _dob == null + ? 'Select a date (optional)' + : Formatters.date(_dob!), + style: TextStyle( + color: _dob == null + ? AppColors.textTertiary + : AppColors.textPrimary, + fontSize: 15, + ), + ), + ), + ), + ), + + if (_serverError != null) ...[ + const SizedBox(height: AppSpacing.sm), + Container( + width: double.infinity, + padding: const EdgeInsets.all(AppSpacing.md), + decoration: BoxDecoration( + color: AppColors.dangerSurface, + borderRadius: AppRadius.brSm, + ), + child: Row(children: [ + const Icon(Icons.error_outline_rounded, + color: AppColors.danger, size: 18), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Text( + _serverError!, + style: const TextStyle( + color: AppColors.danger, + fontSize: 13.5, + ), + ), + ), + ]), + ), + ], + + const SizedBox(height: AppSpacing.xxl), + Row(children: [ + Expanded( + child: PrimaryButton( + label: 'Cancel', + tone: ButtonTone.neutral, + onPressed: + _saving ? null : () => context.pop(), + ), + ), + const SizedBox(width: AppSpacing.md), + Expanded( + flex: 2, + child: PrimaryButton( + label: 'Save & Continue', + icon: Icons.check_rounded, + busy: _saving, + onPressed: _save, + ), + ), + ]), + ], + ), + ), + ), + ), + ), + ), + ); + } +} + +class _Field extends StatelessWidget { + const _Field({ + required this.label, + required this.child, + this.required = false, + }); + + final String label; + final Widget child; + final bool required; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: AppSpacing.lg), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row(children: [ + Text(label, + style: context.text.labelMedium + ?.copyWith(color: AppColors.textSecondary)), + if (required) + const Text(' *', + style: TextStyle(color: AppColors.danger, fontSize: 13)), + if (!required) + Text(' optional', + style: context.text.labelSmall + ?.copyWith(color: AppColors.textTertiary)), + ]), + const SizedBox(height: AppSpacing.sm), + child, + ], + ), + ); + } +} diff --git a/lib/presentation/customer/screens/existing_customer_screen.dart b/lib/presentation/customer/screens/existing_customer_screen.dart new file mode 100644 index 0000000..69f5bc9 --- /dev/null +++ b/lib/presentation/customer/screens/existing_customer_screen.dart @@ -0,0 +1,504 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_animate/flutter_animate.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/constants/app_constants.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/extensions.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/widgets/empty_state.dart'; +import '../../../core/widgets/glass_card.dart'; +import '../../../core/widgets/numeric_keypad.dart'; +import '../../../core/widgets/primary_button.dart'; +import '../../../core/widgets/status_pill.dart'; +import '../../../domain/entities/customer.dart'; +import '../../pos/providers/cart_controller.dart'; +import '../providers/customer_providers.dart'; + +/// Screen 3 — mobile lookup that auto-searches on the tenth digit. +class ExistingCustomerScreen extends ConsumerStatefulWidget { + const ExistingCustomerScreen({super.key}); + + @override + ConsumerState createState() => + _ExistingCustomerScreenState(); +} + +class _ExistingCustomerScreenState + extends ConsumerState { + String _digits = ''; + + void _append(String d) { + if (_digits.length >= AppConstants.mobileNumberLength) return; + setState(() => _digits += d); + if (_digits.length == AppConstants.mobileNumberLength) _search(); + } + + void _backspace() { + if (_digits.isEmpty) return; + setState(() => _digits = _digits.substring(0, _digits.length - 1)); + ref.read(customerLookupProvider.notifier).reset(); + } + + void _clear() { + setState(() => _digits = ''); + ref.read(customerLookupProvider.notifier).reset(); + } + + void _search() => ref.read(customerLookupProvider.notifier).search(_digits); + + void _continueWith(Customer customer) { + ref.read(cartControllerProvider.notifier).attachCustomer(customer); + context.go(AppRoutes.pos); + } + + @override + Widget build(BuildContext context) { + final lookup = ref.watch(customerLookupProvider); + + return Scaffold( + backgroundColor: AppColors.background, + appBar: AppBar( + title: const Text('Find Customer'), + leading: IconButton( + icon: const Icon(Icons.arrow_back_rounded), + onPressed: () => context.pop(), + ), + actions: [ + TextButton.icon( + onPressed: () { + ref.read(cartControllerProvider.notifier).attachCustomer(null); + context.go(AppRoutes.pos); + }, + icon: const Icon(Icons.directions_walk_rounded, + color: Colors.white, size: 18), + label: const Text('Continue as Walk-in', + style: TextStyle(color: Colors.white)), + ), + const SizedBox(width: AppSpacing.lg), + ], + ), + body: Padding( + padding: const EdgeInsets.all(AppSpacing.xxl), + child: context.isCompact + ? SingleChildScrollView( + child: Column(children: [ + _entryPanel(), + const SizedBox(height: AppSpacing.xxl), + // Bound the height: the panel uses Expanded/Spacer + // internally, which a scroll view cannot supply. + SizedBox(height: 480, child: _resultPanel(lookup)), + ]), + ) + : Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded(flex: 4, child: _entryPanel()), + const SizedBox(width: AppSpacing.xxl), + Expanded(flex: 5, child: _resultPanel(lookup)), + ], + ), + ), + ); + } + + Widget _entryPanel() { + return GlassCard( + padding: const EdgeInsets.all(AppSpacing.xxl), + radius: AppRadius.xl, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text('Mobile number', style: context.text.labelMedium), + const SizedBox(height: AppSpacing.md), + _display(), + const SizedBox(height: AppSpacing.xxl), + Center( + child: NumericKeypad( + onKey: _append, + onBackspace: _backspace, + onClear: _clear, + onSubmit: + _digits.length == AppConstants.mobileNumberLength + ? _search + : null, + submitLabel: 'Search', + ), + ), + ], + ), + ); + } + + /// Ten slots so the cashier can see progress at a glance. + Widget _display() { + return Container( + height: 72, + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), + decoration: BoxDecoration( + color: AppColors.primarySurface, + borderRadius: AppRadius.brLg, + border: Border.all(color: AppColors.primaryBorder), + ), + child: Row(children: [ + const Text('+91', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w600, + color: AppColors.textSecondary, + )), + const SizedBox(width: AppSpacing.md), + Expanded( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: List.generate( + AppConstants.mobileNumberLength, + (i) { + final filled = i < _digits.length; + return AnimatedContainer( + duration: AppMotion.fast, + width: 22, + alignment: Alignment.center, + child: Text( + filled ? _digits[i] : '–', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.w700, + color: filled + ? AppColors.textPrimary + : AppColors.textTertiary.withValues(alpha: 0.5), + ), + ), + ); + }, + ), + ), + ), + if (_digits.isNotEmpty) + IconButton( + onPressed: _clear, + icon: const Icon(Icons.close_rounded, size: 20), + color: AppColors.textTertiary, + tooltip: 'Clear', + ), + ]), + ); + } + + Widget _resultPanel(CustomerLookupState state) { + return GlassCard( + padding: const EdgeInsets.all(AppSpacing.xxl), + radius: AppRadius.xl, + child: switch (state) { + LookupIdle() => _idle(), + LookupSearching() => const Center( + child: CircularProgressIndicator(color: AppColors.primary), + ), + LookupFound(:final customer) => _found(customer), + LookupNotFound(:final mobile) => _notFound(mobile), + LookupError(:final message) => EmptyState( + title: 'Something went wrong', + message: message, + emoji: '⚠️', + ), + }, + ); + } + + Widget _idle() { + final recent = ref.watch(recentCustomersProvider); + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text('Recent customers', style: context.text.titleMedium), + const SizedBox(height: AppSpacing.xs), + Text('Tap to select, or key in a mobile number.', + style: context.text.bodySmall), + const SizedBox(height: AppSpacing.lg), + Expanded( + child: recent.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, _) => EmptyState( + title: 'Could not load customers', + message: '$e', + emoji: '⚠️', + compact: true, + ), + data: (customers) => customers.isEmpty + ? const EmptyState( + title: 'No customers yet', + message: 'Register the first one from the welcome screen.', + emoji: '👤', + compact: true, + ) + : ListView.separated( + itemCount: customers.length, + separatorBuilder: (_, __) => + const SizedBox(height: AppSpacing.sm), + itemBuilder: (_, i) => _RecentTile( + customer: customers[i], + onTap: () => _continueWith(customers[i]), + ), + ), + ), + ), + ], + ); + } + + Widget _found(Customer c) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row(children: [ + CircleAvatar( + radius: 30, + backgroundColor: AppColors.primarySurface, + child: Text( + Formatters.initials(c.name), + style: const TextStyle( + color: AppColors.primary, + fontSize: 22, + fontWeight: FontWeight.w700, + ), + ), + ), + const SizedBox(width: AppSpacing.lg), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row(children: [ + Flexible( + child: Text(c.name, + style: context.text.headlineSmall, + overflow: TextOverflow.ellipsis), + ), + const SizedBox(width: AppSpacing.sm), + StatusPill.tier(c.tier), + ]), + const SizedBox(height: 2), + Text('+91 ${Formatters.mobile(c.mobile)}', + style: context.text.bodyMedium + ?.copyWith(color: AppColors.textSecondary)), + ], + ), + ), + ]), + + if (c.isBirthdayToday) ...[ + const SizedBox(height: AppSpacing.lg), + Container( + padding: const EdgeInsets.all(AppSpacing.md), + decoration: BoxDecoration( + color: AppColors.warningSurface, + borderRadius: AppRadius.brSm, + ), + child: const Row(children: [ + Text('🎂', style: TextStyle(fontSize: 18)), + SizedBox(width: AppSpacing.sm), + Text("It's their birthday today — wish them!", + style: TextStyle( + color: AppColors.warning, + fontWeight: FontWeight.w600, + )), + ]), + ), + ], + + const SizedBox(height: AppSpacing.xxl), + Row(children: [ + Expanded( + child: _Stat( + label: 'Loyalty Points', + value: '${c.loyaltyPoints}', + caption: 'Worth ${Formatters.money(c.redeemableValue)}', + icon: Icons.stars_rounded, + color: AppColors.tierGold, + ), + ), + const SizedBox(width: AppSpacing.md), + Expanded( + child: _Stat( + label: 'Lifetime Spend', + value: Formatters.moneyCompact(c.lifetimeSpend), + caption: '${c.visitCount} visits', + icon: Icons.receipt_long_rounded, + color: AppColors.primary, + ), + ), + ]), + + if (c.tier.discountRate > 0) ...[ + const SizedBox(height: AppSpacing.md), + Container( + padding: const EdgeInsets.all(AppSpacing.md), + decoration: BoxDecoration( + color: AppColors.successSurface, + borderRadius: AppRadius.brSm, + ), + child: Row(children: [ + const Icon(Icons.local_offer_rounded, + color: AppColors.success, size: 18), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Text( + '${c.tier.label} members get ' + '${Formatters.percent(c.tier.discountRate)} off ' + 'automatically on every bill.', + style: const TextStyle( + color: AppColors.success, + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + ), + ]), + ), + ], + + const Spacer(), + PrimaryButton( + label: 'Continue to Billing', + icon: Icons.point_of_sale_rounded, + large: true, + onPressed: () => _continueWith(c), + ), + ], + ).animate().fadeIn(duration: 200.ms); + } + + Widget _notFound(String mobile) { + return Column( + children: [ + Expanded( + child: EmptyState( + title: 'No customer found', + message: 'Nobody is registered against ' + '+91 ${Formatters.mobile(mobile)}.', + emoji: '🔍', + ), + ), + PrimaryButton( + label: 'Register Customer', + icon: Icons.person_add_alt_1_rounded, + onPressed: () => context.push( + '${AppRoutes.registerCustomer}?mobile=$mobile', + ), + ), + const SizedBox(height: AppSpacing.md), + PrimaryButton( + label: 'Continue as Walk-in', + icon: Icons.directions_walk_rounded, + tone: ButtonTone.neutral, + onPressed: () { + ref.read(cartControllerProvider.notifier).attachCustomer(null); + context.go(AppRoutes.pos); + }, + ), + ], + ).animate().fadeIn(duration: 200.ms); + } +} + +class _RecentTile extends StatelessWidget { + const _RecentTile({required this.customer, required this.onTap}); + + final Customer customer; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return Material( + color: AppColors.surfaceAlt, + borderRadius: AppRadius.brMd, + child: InkWell( + onTap: onTap, + borderRadius: AppRadius.brMd, + child: Padding( + padding: const EdgeInsets.all(AppSpacing.md), + child: Row(children: [ + CircleAvatar( + radius: 18, + backgroundColor: AppColors.primarySurface, + child: Text( + Formatters.initials(customer.name), + style: const TextStyle( + color: AppColors.primary, + fontSize: 12, + fontWeight: FontWeight.w700, + ), + ), + ), + const SizedBox(width: AppSpacing.md), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(customer.name, + style: context.text.titleSmall, + overflow: TextOverflow.ellipsis), + Text(Formatters.maskedMobile(customer.mobile), + style: context.text.bodySmall), + ], + ), + ), + StatusPill.tier(customer.tier, dense: true), + const SizedBox(width: AppSpacing.sm), + const Icon(Icons.chevron_right_rounded, + color: AppColors.textTertiary), + ]), + ), + ), + ); + } +} + +class _Stat extends StatelessWidget { + const _Stat({ + required this.label, + required this.value, + required this.caption, + required this.icon, + required this.color, + }); + + final String label; + final String value; + final String caption; + final IconData icon; + final Color color; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(AppSpacing.lg), + decoration: BoxDecoration( + color: AppColors.surfaceAlt, + borderRadius: AppRadius.brMd, + border: Border.all(color: AppColors.border), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row(children: [ + Icon(icon, size: 16, color: color), + const SizedBox(width: AppSpacing.xs), + Text(label, + style: context.text.labelSmall + ?.copyWith(color: AppColors.textSecondary)), + ]), + const SizedBox(height: AppSpacing.sm), + Text(value, + style: context.text.headlineSmall?.copyWith(color: color)), + Text(caption, style: context.text.bodySmall), + ], + ), + ); + } +} diff --git a/lib/presentation/modules/screens/customers_view.dart b/lib/presentation/modules/screens/customers_view.dart new file mode 100644 index 0000000..a28e382 --- /dev/null +++ b/lib/presentation/modules/screens/customers_view.dart @@ -0,0 +1,209 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../app/providers.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/widgets/status_pill.dart'; +import '../../../domain/entities/customer.dart'; +import '../widgets/module_widgets.dart'; + +/// Full customer book, independent of the six shown during billing. +final allCustomersProvider = FutureProvider>( + (ref) => ref.watch(customerRepositoryProvider).recent(limit: 200), +); + +class CustomersView extends ConsumerStatefulWidget { + const CustomersView({super.key}); + + @override + ConsumerState createState() => _CustomersViewState(); +} + +class _CustomersViewState extends ConsumerState { + String _query = ''; + MembershipTier? _tier; + + Color _tierColor(MembershipTier t) => switch (t) { + MembershipTier.bronze => AppColors.tierBronze, + MembershipTier.silver => AppColors.tierSilver, + MembershipTier.gold => AppColors.tierGold, + MembershipTier.platinum => AppColors.tierPlatinum, + }; + + @override + Widget build(BuildContext context) { + final all = ref.watch(allCustomersProvider).value ?? const []; + + final filtered = all.where((c) { + final q = _query.trim().toLowerCase(); + final matchesQuery = q.isEmpty || + c.name.toLowerCase().contains(q) || + c.mobile.contains(q); + return matchesQuery && (_tier == null || c.tier == _tier); + }).toList(); + + final lifetime = all.fold(0, (s, c) => s + c.lifetimeSpend); + final points = all.fold(0, (s, c) => s + c.loyaltyPoints); + + return ModulePage( + children: [ + Wrap( + spacing: AppSpacing.lg, + runSpacing: AppSpacing.lg, + children: [ + StatTile( + label: 'Total Customers', + value: '${all.length}', + icon: Icons.people_alt_rounded, + caption: 'registered', + ), + StatTile( + label: 'Lifetime Value', + value: Formatters.moneyCompact(lifetime), + icon: Icons.payments_rounded, + color: AppColors.success, + caption: 'all customers', + ), + StatTile( + label: 'Points Outstanding', + value: '$points', + icon: Icons.stars_rounded, + color: AppColors.tierGold, + caption: 'worth ${Formatters.money(points * 0.25)}', + ), + StatTile( + label: 'Avg Spend', + value: Formatters.money(all.isEmpty ? 0 : lifetime / all.length), + icon: Icons.trending_up_rounded, + color: AppColors.info, + caption: 'per customer', + ), + ], + ), + const SizedBox(height: AppSpacing.lg), + + PanelCard( + title: 'Tier distribution', + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final t in MembershipTier.values) + ProgressRow( + label: '${t.label} · ' + '${(t.discountRate * 100).toStringAsFixed(0)}% off', + value: '${all.where((c) => c.tier == t).length}', + fraction: all.isEmpty + ? 0 + : all.where((c) => c.tier == t).length / all.length, + color: _tierColor(t), + ), + ], + ), + ), + const SizedBox(height: AppSpacing.lg), + + PanelCard( + title: 'Customer book', + subtitle: '${filtered.length} shown', + action: FilledButton.icon( + onPressed: () {}, + icon: const Icon(Icons.person_add_alt_1_rounded, size: 17), + label: const Text('Add customer'), + style: FilledButton.styleFrom( + backgroundColor: AppColors.primary, + minimumSize: const Size(0, 40), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TextField( + onChanged: (v) => setState(() => _query = v), + decoration: const InputDecoration( + hintText: 'Search by name or mobile number…', + prefixIcon: Icon(Icons.search_rounded), + isDense: true, + ), + ), + const SizedBox(height: AppSpacing.md), + Wrap( + spacing: AppSpacing.sm, + runSpacing: AppSpacing.sm, + children: [ + ChoiceChip( + label: const Text('All tiers'), + selected: _tier == null, + onSelected: (_) => setState(() => _tier = null), + labelStyle: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: _tier == null + ? Colors.white + : AppColors.textSecondary, + ), + ), + for (final t in MembershipTier.values) + ChoiceChip( + label: Text(t.label), + selected: _tier == t, + onSelected: (_) => + setState(() => _tier = _tier == t ? null : t), + labelStyle: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: _tier == t + ? Colors.white + : AppColors.textSecondary, + ), + ), + ], + ), + const SizedBox(height: AppSpacing.lg), + ResponsiveTable( + columns: const [ + TableCol('Customer', flex: 4), + TableCol('Mobile', flex: 3, priority: 1), + TableCol('Tier', flex: 2), + TableCol('Points', flex: 2, numeric: true, priority: 1), + TableCol('Lifetime', flex: 2, numeric: true), + TableCol('Visits', flex: 2, numeric: true, priority: 1), + ], + rows: filtered + .map((c) => [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + CircleAvatar( + radius: 14, + backgroundColor: AppColors.primarySurface, + child: Text( + Formatters.initials(c.name), + style: const TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w700, + color: AppColors.primary, + ), + ), + ), + const SizedBox(width: AppSpacing.sm), + Flexible(child: Cell(c.name, bold: true)), + ], + ), + Cell(Formatters.mobile(c.mobile), mono: true), + StatusPill.tier(c.tier, dense: true), + Cell('${c.loyaltyPoints}', mono: true), + Cell(Formatters.moneyCompact(c.lifetimeSpend), + mono: true, bold: true), + Cell('${c.visitCount}', mono: true), + ]) + .toList(), + ), + ], + ), + ), + ], + ); + } +} diff --git a/lib/presentation/modules/screens/events_view.dart b/lib/presentation/modules/screens/events_view.dart new file mode 100644 index 0000000..85455bc --- /dev/null +++ b/lib/presentation/modules/screens/events_view.dart @@ -0,0 +1,287 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/widgets/primary_button.dart'; +import '../../../domain/entities/sync_event.dart'; +import '../../../domain/entities/transaction.dart'; +import '../../sync/providers/sync_controller.dart'; +import '../widgets/module_widgets.dart'; + +/// The terminal's outbound half: what today produced, and what has been sent. +class EventsView extends ConsumerWidget { + const EventsView({super.key}); + + static Color statusColor(SyncStatus s) => switch (s) { + SyncStatus.synced => AppColors.success, + SyncStatus.failed => AppColors.danger, + SyncStatus.syncing => AppColors.info, + SyncStatus.pending => AppColors.warning, + }; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final report = ref.watch(shiftReportProvider); + final events = ref.watch(syncEventsProvider); + final pushing = ref.watch(reportPushProvider); + + return ModulePage( + children: [ + Wrap( + spacing: AppSpacing.lg, + runSpacing: AppSpacing.lg, + children: [ + StatTile( + label: 'Bills Today', + value: '${report.billCount}', + icon: Icons.receipt_long_rounded, + caption: report.firstBillAt == null + ? 'no sales yet' + : '${Formatters.time(report.firstBillAt!)} – ' + '${Formatters.time(report.lastBillAt!)}', + ), + StatTile( + label: 'Items Sold', + value: report.itemCount.toStringAsFixed(0), + icon: Icons.shopping_basket_rounded, + color: AppColors.info, + caption: 'units across all bills', + ), + StatTile( + label: "Today's Sales", + value: Formatters.money(report.grossSales), + icon: Icons.payments_rounded, + color: AppColors.success, + caption: 'gross takings', + ), + StatTile( + label: 'Average Basket', + value: Formatters.money(report.averageBasket), + icon: Icons.trending_up_rounded, + color: AppColors.tierGold, + caption: 'per bill', + ), + ], + ), + const SizedBox(height: AppSpacing.lg), + + PanelCard( + title: 'Shift report', + subtitle: '${Formatters.date(report.businessDate)} · ' + '${report.cashierName} · ${report.terminalId}', + action: TagChip( + report.isEmpty ? 'Nothing to send' : 'Ready to push', + color: report.isEmpty ? AppColors.textSecondary : AppColors.warning, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + _row('Bills', '${report.billCount}'), + _row('Items sold', report.itemCount.toStringAsFixed(0)), + _row('Gross sales', Formatters.money(report.grossSales)), + _row('Net of tax', Formatters.money(report.netOfTax)), + _row('GST collected', Formatters.money(report.taxCollected)), + _row('Discount given', Formatters.money(report.discountGiven)), + _row('Round off', Formatters.money(report.roundOff)), + _row('Points issued', '${report.loyaltyPointsIssued}'), + _row('Points redeemed', '${report.loyaltyPointsRedeemed}'), + + if (report.paymentBreakdown.isNotEmpty) ...[ + const Divider(height: AppSpacing.xxl), + const Align( + alignment: Alignment.centerLeft, + child: Text( + 'By payment method', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: AppColors.textSecondary, + ), + ), + ), + const SizedBox(height: AppSpacing.sm), + for (final e in report.paymentBreakdown.entries) + ProgressRow( + label: '${e.key.emoji} ${e.key.label}', + value: Formatters.money(e.value), + fraction: report.grossSales <= 0 + ? 0 + : e.value / report.grossSales, + color: _methodColor(e.key), + ), + ], + + const SizedBox(height: AppSpacing.xl), + PrimaryButton( + label: 'Push report to server', + icon: Icons.cloud_upload_rounded, + large: true, + busy: pushing, + onPressed: report.isEmpty + ? null + : () async { + final event = await ref + .read(reportPushProvider.notifier) + .pushToday(); + if (!context.mounted) return; + final ok = event.status == SyncStatus.synced; + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar( + backgroundColor: + ok ? AppColors.success : AppColors.danger, + content: Text( + ok + ? 'Shift report sent.' + : 'Push failed — the report is still saved ' + 'on this terminal.', + ), + )); + }, + ), + const SizedBox(height: AppSpacing.md), + const Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.shield_outlined, + size: 15, color: AppColors.textTertiary), + SizedBox(width: AppSpacing.sm), + Expanded( + child: Text( + 'A failed push never discards data. The report stays ' + 'queued below and can be retried at any time.', + style: TextStyle( + fontSize: 12, + color: AppColors.textTertiary, + height: 1.5, + ), + ), + ), + ], + ), + ], + ), + ), + const SizedBox(height: AppSpacing.lg), + + PanelCard( + title: 'Event log', + subtitle: '${events.length} recorded · ' + '${events.where((e) => e.status != SyncStatus.synced).length} ' + 'outstanding', + child: events.isEmpty + ? const Padding( + padding: EdgeInsets.symmetric(vertical: AppSpacing.lg), + child: Text( + 'No sync activity yet. Importing the catalogue or pushing ' + 'a report will appear here.', + style: TextStyle(color: AppColors.textTertiary), + ), + ) + : ResponsiveTable( + columns: const [ + TableCol('Event', flex: 3), + TableCol('Detail', flex: 5, priority: 1), + TableCol('Time', flex: 2, numeric: true, priority: 1), + TableCol('Status', flex: 2, numeric: true), + ], + rows: events + .map((e) => [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + e.type.isInbound + ? Icons.cloud_download_rounded + : Icons.cloud_upload_rounded, + size: 15, + color: AppColors.textSecondary, + ), + const SizedBox(width: AppSpacing.sm), + Flexible(child: Cell(e.type.label, bold: true)), + ], + ), + Cell( + e.error ?? e.summary, + color: e.error != null + ? AppColors.danger + : AppColors.textSecondary, + ), + Cell(Formatters.time(e.createdAt), + color: AppColors.textTertiary), + e.status == SyncStatus.failed + ? _RetryButton(eventId: e.id) + : TagChip( + e.status.label, + color: statusColor(e.status), + ), + ]) + .toList(), + ), + ), + ], + ); + } + + static Color _methodColor(PaymentMethod m) => switch (m) { + PaymentMethod.cash => AppColors.success, + PaymentMethod.card => AppColors.info, + PaymentMethod.upi => AppColors.primary, + PaymentMethod.wallet => AppColors.warning, + PaymentMethod.giftCard => AppColors.tierGold, + PaymentMethod.loyalty => AppColors.tierSilver, + }; + + Widget _row(String label, String value) => Padding( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs + 2), + child: Row( + children: [ + Expanded( + child: Text( + label, + style: const TextStyle( + fontSize: 13.5, + color: AppColors.textSecondary, + ), + ), + ), + const SizedBox(width: AppSpacing.md), + Text( + value, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + ), + ), + ], + ), + ); +} + +class _RetryButton extends ConsumerWidget { + const _RetryButton({required this.eventId}); + + final String eventId; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final busy = ref.watch(reportPushProvider); + + return TextButton.icon( + onPressed: busy + ? null + : () => ref.read(reportPushProvider.notifier).retry(eventId), + icon: const Icon(Icons.refresh_rounded, size: 15), + label: const Text('Retry', style: TextStyle(fontSize: 12.5)), + style: TextButton.styleFrom( + foregroundColor: AppColors.danger, + minimumSize: const Size(0, 30), + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.sm), + ), + ); + } +} diff --git a/lib/presentation/modules/screens/product_import_view.dart b/lib/presentation/modules/screens/product_import_view.dart new file mode 100644 index 0000000..830b4ce --- /dev/null +++ b/lib/presentation/modules/screens/product_import_view.dart @@ -0,0 +1,338 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../app/providers.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/widgets/primary_button.dart'; +import '../../../domain/entities/product.dart'; +import '../../pos/providers/catalog_providers.dart'; +import '../../pos/providers/navigation_provider.dart'; +import '../../sync/providers/sync_controller.dart'; +import '../widgets/module_widgets.dart'; + +/// Pulls the catalogue onto the terminal. +/// +/// This is the first thing a cashier does at the start of a session — until it +/// succeeds there is nothing to bill. Once imported, everything runs locally. +class ProductImportView extends ConsumerWidget { + const ProductImportView({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final state = ref.watch(catalogueImportProvider); + final ready = ref.watch(catalogueReadyProvider); + final lastImport = ref.watch(lastImportAtProvider); + final products = ref.watch(allProductsProvider).value ?? const []; + final revision = ref.watch(syncRepositoryProvider).catalogueRevision; + + return ModulePage( + children: [ + if (!ready) _NotImportedBanner(state: state), + + if (ready) ...[ + Wrap( + spacing: AppSpacing.lg, + runSpacing: AppSpacing.lg, + children: [ + StatTile( + label: 'Products Loaded', + value: '${products.length}', + icon: Icons.inventory_2_rounded, + color: AppColors.success, + caption: 'available offline', + ), + StatTile( + label: 'Catalogue Revision', + value: revision ?? '—', + icon: Icons.tag_rounded, + color: AppColors.info, + caption: 'server version', + ), + StatTile( + label: 'Last Imported', + value: lastImport == null + ? '—' + : Formatters.time(lastImport), + icon: Icons.schedule_rounded, + caption: lastImport == null + ? 'never' + : Formatters.date(lastImport), + ), + StatTile( + label: 'Stock Value', + value: Formatters.moneyCompact( + products.fold(0, (s, p) => s + p.price * p.stock), + ), + icon: Icons.savings_rounded, + color: AppColors.tierGold, + caption: 'at selling price', + ), + ], + ), + const SizedBox(height: AppSpacing.lg), + ], + + PanelCard( + title: ready ? 'Re-import catalogue' : 'Import catalogue', + subtitle: ready + ? 'Pulls the latest prices and products. Stock already sold on ' + 'this terminal is preserved.' + : 'Connect once to load products, then bill offline all day.', + child: _ImportPanel(state: state, ready: ready), + ), + + if (ready) ...[ + const SizedBox(height: AppSpacing.lg), + PanelCard( + title: 'Imported products', + subtitle: '${products.length} items on this terminal', + child: ResponsiveTable( + columns: const [ + TableCol('Product', flex: 4), + TableCol('SKU', flex: 3, priority: 1), + TableCol('Category', flex: 2, priority: 1), + TableCol('Price', flex: 2, numeric: true), + TableCol('Stock', flex: 2, numeric: true), + ], + rows: products + .map((p) => [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(p.emoji, + style: const TextStyle(fontSize: 17)), + const SizedBox(width: AppSpacing.sm), + Flexible(child: Cell(p.name, bold: true)), + ], + ), + Cell(p.sku, color: AppColors.textTertiary), + TagChip(p.category.label, + color: AppColors.textSecondary), + Cell(Formatters.money(p.price), mono: true, bold: true), + TagChip( + p.isOutOfStock + ? 'Out' + : '${p.stock.toStringAsFixed(0)} ${p.unit.symbol}', + color: p.isOutOfStock + ? AppColors.danger + : (p.isLowStock + ? AppColors.warning + : AppColors.success), + ), + ]) + .toList(), + ), + ), + ], + ], + ); + } +} + +class _NotImportedBanner extends StatelessWidget { + const _NotImportedBanner({required this.state}); + + final ImportState state; + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.only(bottom: AppSpacing.lg), + padding: const EdgeInsets.all(AppSpacing.lg), + decoration: BoxDecoration( + color: AppColors.warningSurface, + borderRadius: AppRadius.brLg, + border: Border.all(color: AppColors.warning.withValues(alpha: 0.35)), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon(Icons.cloud_download_outlined, + color: AppColors.warning, size: 22), + const SizedBox(width: AppSpacing.md), + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'No catalogue on this terminal', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + ), + ), + SizedBox(height: 2), + Text( + 'Billing is disabled until products are imported. This is ' + 'the only step that needs a connection at the start of a ' + 'shift.', + style: TextStyle( + fontSize: 13, + color: AppColors.textSecondary, + height: 1.5, + ), + ), + ], + ), + ), + ], + ), + ); + } +} + +class _ImportPanel extends ConsumerWidget { + const _ImportPanel({required this.state, required this.ready}); + + final ImportState state; + final bool ready; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final running = state is ImportRunning; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + if (state is ImportRunning) ...[ + Text( + (state as ImportRunning).stage, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w500, + color: AppColors.textSecondary, + ), + ), + const SizedBox(height: AppSpacing.sm), + ClipRRect( + borderRadius: AppRadius.brPill, + child: LinearProgressIndicator( + value: (state as ImportRunning).progress, + minHeight: 8, + backgroundColor: AppColors.divider, + valueColor: + const AlwaysStoppedAnimation(AppColors.primary), + ), + ), + const SizedBox(height: AppSpacing.lg), + ], + + if (state is ImportFailed) ...[ + Container( + padding: const EdgeInsets.all(AppSpacing.md), + margin: const EdgeInsets.only(bottom: AppSpacing.lg), + decoration: BoxDecoration( + color: AppColors.dangerSurface, + borderRadius: AppRadius.brSm, + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon(Icons.wifi_off_rounded, + color: AppColors.danger, size: 18), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Text( + (state as ImportFailed).message, + style: const TextStyle( + color: AppColors.danger, + fontSize: 13, + height: 1.45, + ), + ), + ), + ], + ), + ), + ], + + if (state is ImportDone) ...[ + Container( + padding: const EdgeInsets.all(AppSpacing.md), + margin: const EdgeInsets.only(bottom: AppSpacing.lg), + decoration: BoxDecoration( + color: AppColors.successSurface, + borderRadius: AppRadius.brSm, + ), + child: Row( + children: [ + const Icon(Icons.check_circle_outline_rounded, + color: AppColors.success, size: 18), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Text( + (state as ImportDone).event.summary, + style: const TextStyle( + color: AppColors.success, + fontSize: 13, + fontWeight: FontWeight.w500, + ), + ), + ), + ], + ), + ), + ], + + // Wrap so the buttons stack rather than overflow on a narrow panel. + Wrap( + spacing: AppSpacing.md, + runSpacing: AppSpacing.md, + children: [ + SizedBox( + width: 240, + child: PrimaryButton( + label: ready ? 'Re-import now' : 'Import catalogue', + icon: Icons.cloud_download_rounded, + large: true, + busy: running, + onPressed: running + ? null + : () => ref.read(catalogueImportProvider.notifier).run(), + ), + ), + if (ready && !running) + SizedBox( + width: 200, + child: PrimaryButton( + label: 'Start billing', + icon: Icons.point_of_sale_rounded, + large: true, + tone: ButtonTone.ghost, + onPressed: () => ref + .read(activeModuleProvider.notifier) + .state = PosModule.pos, + ), + ), + ], + ), + + const SizedBox(height: AppSpacing.lg), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon(Icons.info_outline_rounded, + size: 15, color: AppColors.textTertiary), + const SizedBox(width: AppSpacing.sm), + const Expanded( + child: Text( + 'After this import the terminal works entirely offline. ' + 'Sales, customers and parked bills are held locally and are ' + 'only sent when you push the shift report at sign-out.', + style: TextStyle( + fontSize: 12, + color: AppColors.textTertiary, + height: 1.5, + ), + ), + ), + ], + ), + ], + ); + } +} diff --git a/lib/presentation/modules/screens/promos_view.dart b/lib/presentation/modules/screens/promos_view.dart new file mode 100644 index 0000000..69290a4 --- /dev/null +++ b/lib/presentation/modules/screens/promos_view.dart @@ -0,0 +1,202 @@ +import 'package:flutter/material.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../widgets/module_widgets.dart'; + +/// Discount rules and campaigns. +class PromosView extends StatefulWidget { + const PromosView({super.key}); + + @override + State createState() => _PromosViewState(); +} + +class _PromosViewState extends State { + final Set _enabled = {'WEEKEND10', 'DAIRY5', 'FESTIVE'}; + + static const _campaigns = [ + ( + 'WEEKEND10', + 'Weekend Saver', + '10% off bills above ₹500', + 'Sat–Sun', + 412, + AppColors.primary, + ), + ( + 'DAIRY5', + 'Dairy Days', + '5% off all dairy products', + 'Ends 31 Aug', + 286, + AppColors.info, + ), + ( + 'FESTIVE', + 'Festive Bonus', + 'Double loyalty points', + 'Ends 15 Sep', + 178, + AppColors.tierGold, + ), + ( + 'NEWCUST', + 'First Purchase', + '₹50 off the first bill', + 'Always on', + 94, + AppColors.success, + ), + ]; + + @override + Widget build(BuildContext context) { + return ModulePage( + children: [ + Wrap( + spacing: AppSpacing.lg, + runSpacing: AppSpacing.lg, + children: [ + StatTile( + label: 'Active Campaigns', + value: '${_enabled.length}', + icon: Icons.campaign_rounded, + caption: 'of ${_campaigns.length} configured', + ), + StatTile( + label: 'Redemptions', + value: '970', + icon: Icons.confirmation_number_rounded, + color: AppColors.info, + caption: 'this month', + ), + StatTile( + label: 'Discount Given', + value: '₹48,240', + icon: Icons.local_offer_rounded, + color: AppColors.warning, + caption: '2.6% of sales', + ), + StatTile( + label: 'Incremental Sales', + value: '₹2.14L', + icon: Icons.trending_up_rounded, + color: AppColors.success, + delta: '+18%', + caption: 'attributed', + ), + ], + ), + const SizedBox(height: AppSpacing.lg), + + PanelCard( + title: 'Campaigns', + subtitle: 'Toggle a rule to apply it at the till immediately', + action: FilledButton.icon( + onPressed: () {}, + icon: const Icon(Icons.add_rounded, size: 18), + label: const Text('New campaign'), + style: FilledButton.styleFrom( + backgroundColor: AppColors.primary, + minimumSize: const Size(0, 40), + ), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final c in _campaigns) + Container( + margin: const EdgeInsets.only(bottom: AppSpacing.sm), + padding: const EdgeInsets.all(AppSpacing.md), + decoration: BoxDecoration( + color: AppColors.surfaceAlt, + borderRadius: AppRadius.brMd, + border: Border.all(color: AppColors.border), + ), + // Wrap prevents collision when the panel is narrow. + child: Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: AppSpacing.md, + runSpacing: AppSpacing.sm, + children: [ + SizedBox( + width: 320, + child: Row( + children: [ + Container( + width: 38, + height: 38, + decoration: BoxDecoration( + color: c.$6.withValues(alpha: 0.12), + borderRadius: AppRadius.brSm, + ), + child: Icon(Icons.sell_rounded, + size: 18, color: c.$6), + ), + const SizedBox(width: AppSpacing.md), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + c.$2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + Text( + c.$3, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 12.5, + color: AppColors.textSecondary, + ), + ), + ], + ), + ), + ], + ), + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + TagChip(c.$1, color: c.$6), + const SizedBox(width: AppSpacing.sm), + TagChip(c.$4, color: AppColors.textSecondary), + const SizedBox(width: AppSpacing.sm), + Text( + '${c.$5} used', + style: const TextStyle( + fontSize: 12, + color: AppColors.textTertiary, + ), + ), + const SizedBox(width: AppSpacing.sm), + Switch( + value: _enabled.contains(c.$1), + onChanged: (v) => setState(() { + if (v) { + _enabled.add(c.$1); + } else { + _enabled.remove(c.$1); + } + }), + ), + ], + ), + ], + ), + ), + ], + ), + ), + ], + ); + } +} diff --git a/lib/presentation/modules/screens/settings_view.dart b/lib/presentation/modules/screens/settings_view.dart new file mode 100644 index 0000000..0c052c3 --- /dev/null +++ b/lib/presentation/modules/screens/settings_view.dart @@ -0,0 +1,322 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../app/providers.dart'; +import '../../../core/constants/app_constants.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../domain/entities/store_account.dart'; +import '../../../domain/entities/sync_event.dart'; +import '../../auth/providers/auth_controller.dart'; +import '../../sync/providers/sync_controller.dart'; +import '../widgets/module_widgets.dart'; + +/// Terminal and store configuration. +class SettingsView extends ConsumerStatefulWidget { + const SettingsView({super.key}); + + @override + ConsumerState createState() => _SettingsViewState(); +} + +class _SettingsViewState extends ConsumerState { + bool _scannerSound = true; + bool _autoPrint = true; + bool _openDrawer = true; + bool _roundOff = true; + bool _autoLoyalty = true; + bool _offline = false; + + @override + Widget build(BuildContext context) { + final store = ref.watch(currentStoreProvider); + final user = ref.watch(currentUserProvider); + + return ModulePage( + children: [ + LayoutBuilder( + builder: (context, constraints) { + final wide = constraints.maxWidth >= 1040; + + final left = Column( + children: [ + _storeCard(store), + const SizedBox(height: AppSpacing.lg), + _taxCard(), + const SizedBox(height: AppSpacing.lg), + _loyaltyCard(), + ], + ); + final right = Column( + children: [ + _hardwareCard(), + const SizedBox(height: AppSpacing.lg), + _connectivityCard(), + const SizedBox(height: AppSpacing.lg), + _staffCard(store, user), + const SizedBox(height: AppSpacing.lg), + _aboutCard(), + ], + ); + + if (!wide) { + return Column( + children: [left, const SizedBox(height: AppSpacing.lg), right], + ); + } + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: left), + const SizedBox(width: AppSpacing.lg), + Expanded(child: right), + ], + ); + }, + ), + ], + ); + } + + Widget _storeCard(StoreAccount? store) => PanelCard( + title: 'Store details', + subtitle: 'Printed on every invoice', + action: TextButton(onPressed: () {}, child: const Text('Edit')), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _row('Store name', store?.name ?? AppConstants.storeName), + _row('Address', store?.address ?? AppConstants.storeAddress), + _row('GSTIN', store?.gstin ?? AppConstants.storeGstin, mono: true), + _row('Phone', store?.phone ?? AppConstants.storePhone, mono: true), + _row('Plan', store?.plan ?? 'Business'), + ], + ), + ); + + Widget _taxCard() => PanelCard( + title: 'Tax & pricing', + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _row( + 'Default GST slab', + Formatters.percent(AppConstants.defaultGstRate), + ), + _row('Prices include tax', 'Yes'), + _toggle( + 'Round bills to nearest rupee', + 'Shows the adjustment as a Round Off line', + _roundOff, + (v) => setState(() => _roundOff = v), + ), + ], + ), + ); + + Widget _loyaltyCard() => PanelCard( + title: 'Loyalty programme', + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _row( + 'Earn rate', + '1 point per ' + '${Formatters.money(AppConstants.loyaltyRupeesPerPoint)}', + ), + _row( + 'Point value', + Formatters.money(AppConstants.loyaltyPointValue), + ), + _toggle( + 'Apply tier discount automatically', + 'Silver 2%, Gold 5%, Platinum 8%', + _autoLoyalty, + (v) => setState(() => _autoLoyalty = v), + ), + ], + ), + ); + + Widget _hardwareCard() => PanelCard( + title: 'Hardware & peripherals', + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _toggle( + 'Scanner beep', + 'Audible confirmation on every scan', + _scannerSound, + (v) => setState(() => _scannerSound = v), + ), + _toggle( + 'Print receipt automatically', + 'Sends to the default roll printer with no dialog', + _autoPrint, + (v) => setState(() => _autoPrint = v), + ), + _toggle( + 'Open cash drawer on cash sales', + 'Sends the ESC/POS kick pulse', + _openDrawer, + (v) => setState(() => _openDrawer = v), + ), + const Divider(height: AppSpacing.xxl), + _row('Receipt printer', 'EPSON TM-T82 (default)'), + _row('Barcode scanner', 'Keyboard wedge · detected'), + _row('Cash drawer', 'Connected via printer'), + ], + ), + ); + + Widget _staffCard(StoreAccount? store, StaffUser? current) => PanelCard( + title: 'Users & roles', + action: TextButton(onPressed: () {}, child: const Text('Manage')), + child: ResponsiveTable( + stackBelow: 360, + columns: const [ + TableCol('Name', flex: 3), + TableCol('Role', flex: 3), + TableCol('', flex: 2, numeric: true), + ], + rows: (store?.staff ?? const []) + .map((s) => [ + Cell(s.name, bold: true), + Cell(s.role.label, color: AppColors.textSecondary), + s.id == current?.id + ? const TagChip('Signed in', + color: AppColors.success) + : const SizedBox.shrink(), + ]) + .toList(), + ), + ); + + Widget _connectivityCard() { + final ready = ref.watch(catalogueReadyProvider); + final lastImport = ref.watch(lastImportAtProvider); + final outstanding = ref + .watch(syncEventsProvider) + .where((e) => e.status != SyncStatus.synced) + .length; + + return PanelCard( + title: 'Connectivity & sync', + subtitle: 'This terminal only needs a connection to import the ' + 'catalogue and to push the shift report.', + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _row('Catalogue', ready ? 'Loaded' : 'Not imported'), + _row( + 'Last import', + lastImport == null ? 'Never' : Formatters.dateTime(lastImport), + ), + _row('Outstanding pushes', '$outstanding'), + _toggle( + 'Simulate offline', + 'Forces import and push to fail, so you can confirm nothing is ' + 'lost when the network drops', + _offline, + (v) { + setState(() => _offline = v); + ref.read(remoteCatalogueProvider).simulateOffline = v; + ref.read(remoteReportSinkProvider).simulateOffline = v; + }, + ), + ], + ), + ); + } + + Widget _aboutCard() => PanelCard( + title: 'About', + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _row('Application', '${AppConstants.appName} 1.0.0'), + _row('Terminal', 'TERM-01'), + _row('Data store', 'Local — offline first'), + const SizedBox(height: AppSpacing.md), + SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + onPressed: () {}, + icon: const Icon(Icons.sync_rounded, size: 17), + label: const Text('Check for updates'), + ), + ), + ], + ), + ); + + Widget _row(String label, String value, {bool mono = false}) => Padding( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.sm), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 148, + child: Text( + label, + style: const TextStyle( + fontSize: 13, + color: AppColors.textSecondary, + ), + ), + ), + Expanded( + child: Text( + value, + textAlign: TextAlign.right, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + fontFamily: mono ? 'monospace' : null, + ), + ), + ), + ], + ), + ); + + Widget _toggle( + String title, + String subtitle, + bool value, + ValueChanged onChanged, + ) => + Padding( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w500, + ), + ), + Text( + subtitle, + style: const TextStyle( + fontSize: 11.5, + color: AppColors.textTertiary, + height: 1.4, + ), + ), + ], + ), + ), + const SizedBox(width: AppSpacing.md), + Switch(value: value, onChanged: onChanged), + ], + ), + ); +} diff --git a/lib/presentation/modules/widgets/module_widgets.dart b/lib/presentation/modules/widgets/module_widgets.dart new file mode 100644 index 0000000..69c4a62 --- /dev/null +++ b/lib/presentation/modules/widgets/module_widgets.dart @@ -0,0 +1,580 @@ +import 'package:flutter/material.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; + +/// Scrollable page body shared by every module screen. +/// +/// Always scrolls vertically, so no module can overflow no matter how short +/// the viewport gets. +class ModulePage extends StatelessWidget { + const ModulePage({ + super.key, + required this.children, + this.padding = AppSpacing.xxl, + }); + + final List children; + final double padding; + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.all(padding), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: children, + ), + ); + } +} + +/// KPI card. Designed to sit inside a [Wrap] so it reflows instead of +/// overflowing when the window narrows. +class StatTile extends StatelessWidget { + const StatTile({ + super.key, + required this.label, + required this.value, + required this.icon, + this.color = AppColors.primary, + this.delta, + this.deltaPositive = true, + this.caption, + this.width = 232, + }); + + final String label; + final String value; + final IconData icon; + final Color color; + final String? delta; + final bool deltaPositive; + final String? caption; + final double width; + + @override + Widget build(BuildContext context) { + return Container( + width: width, + padding: const EdgeInsets.all(AppSpacing.lg), + decoration: BoxDecoration( + color: AppColors.surface, + borderRadius: AppRadius.brLg, + border: Border.all(color: AppColors.border), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: color.withValues(alpha: 0.12), + borderRadius: AppRadius.brSm, + ), + child: Icon(icon, size: 17, color: color), + ), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Text( + label, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w500, + color: AppColors.textSecondary, + ), + ), + ), + ], + ), + const SizedBox(height: AppSpacing.md), + FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerLeft, + child: Text(value, style: AppTypography.money(24)), + ), + if (delta != null || caption != null) ...[ + const SizedBox(height: AppSpacing.xs), + Row( + children: [ + if (delta != null) ...[ + Icon( + deltaPositive + ? Icons.trending_up_rounded + : Icons.trending_down_rounded, + size: 14, + color: + deltaPositive ? AppColors.success : AppColors.danger, + ), + const SizedBox(width: 3), + Text( + delta!, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: + deltaPositive ? AppColors.success : AppColors.danger, + ), + ), + const SizedBox(width: AppSpacing.xs), + ], + if (caption != null) + Expanded( + child: Text( + caption!, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 11.5, + color: AppColors.textTertiary, + ), + ), + ), + ], + ), + ], + ], + ), + ); + } +} + +/// Titled container for a block of module content. +class PanelCard extends StatelessWidget { + const PanelCard({ + super.key, + required this.title, + required this.child, + this.subtitle, + this.action, + this.padding = AppSpacing.lg, + }); + + final String title; + final Widget child; + final String? subtitle; + final Widget? action; + final double padding; + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration( + color: AppColors.surface, + borderRadius: AppRadius.brLg, + border: Border.all(color: AppColors.border), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: EdgeInsets.fromLTRB(padding, padding, padding, AppSpacing.md), + // Wrap so a long title plus an action never collide. + child: Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: AppSpacing.md, + runSpacing: AppSpacing.sm, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 15.5, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + ), + ), + if (subtitle != null) + Text( + subtitle!, + style: const TextStyle( + fontSize: 12.5, + color: AppColors.textTertiary, + ), + ), + ], + ), + if (action != null) action!, + ], + ), + ), + const Divider(height: 1), + Padding(padding: EdgeInsets.all(padding), child: child), + ], + ), + ); + } +} + +/// One column of a [ResponsiveTable]. +class TableCol { + const TableCol( + this.label, { + this.flex = 2, + this.numeric = false, + this.priority = 0, + }); + + final String label; + final int flex; + final bool numeric; + + /// Higher numbers are dropped first as the table narrows. + final int priority; +} + +/// Table that degrades into stacked cards rather than overflowing. +/// +/// Above [stackBelow] it renders as aligned columns; below, each row becomes a +/// label/value card. Low-priority columns are hidden at intermediate widths. +class ResponsiveTable extends StatelessWidget { + const ResponsiveTable({ + super.key, + required this.columns, + required this.rows, + this.stackBelow = 620, + this.hideSecondaryBelow = 900, + this.onRowTap, + }); + + final List columns; + + /// Each row must supply exactly one cell per column. + final List> rows; + + final double stackBelow; + final double hideSecondaryBelow; + final void Function(int index)? onRowTap; + + @override + Widget build(BuildContext context) { + if (rows.isEmpty) { + return const Padding( + padding: EdgeInsets.symmetric(vertical: AppSpacing.xxl), + child: Center( + child: Text( + 'Nothing to show yet.', + style: TextStyle(color: AppColors.textTertiary), + ), + ), + ); + } + + return LayoutBuilder( + builder: (context, constraints) { + final w = constraints.maxWidth; + + if (w < stackBelow) return _stacked(); + + final visible = [ + for (var i = 0; i < columns.length; i++) + if (w >= hideSecondaryBelow || columns[i].priority == 0) i, + ]; + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.only(bottom: AppSpacing.sm), + child: Row( + children: [ + for (final i in visible) + Expanded( + flex: columns[i].flex, + child: Text( + columns[i].label.toUpperCase(), + textAlign: + columns[i].numeric ? TextAlign.right : TextAlign.left, + overflow: TextOverflow.ellipsis, + style: AppTypography.sectionLabel(), + ), + ), + ], + ), + ), + const Divider(height: 1), + for (var r = 0; r < rows.length; r++) + InkWell( + onTap: onRowTap == null ? null : () => onRowTap!(r), + borderRadius: AppRadius.brXs, + child: Container( + padding: + const EdgeInsets.symmetric(vertical: AppSpacing.md), + decoration: const BoxDecoration( + border: + Border(bottom: BorderSide(color: AppColors.divider)), + ), + child: Row( + children: [ + for (final i in visible) + Expanded( + flex: columns[i].flex, + child: Align( + alignment: columns[i].numeric + ? Alignment.centerRight + : Alignment.centerLeft, + child: rows[r][i], + ), + ), + ], + ), + ), + ), + ], + ); + }, + ); + } + + Widget _stacked() { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (var r = 0; r < rows.length; r++) + Container( + margin: const EdgeInsets.only(bottom: AppSpacing.sm), + padding: const EdgeInsets.all(AppSpacing.md), + decoration: BoxDecoration( + color: AppColors.surfaceAlt, + borderRadius: AppRadius.brSm, + border: Border.all(color: AppColors.border), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (var c = 0; c < columns.length; c++) + Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 104, + child: Text( + columns[c].label, + style: const TextStyle( + fontSize: 12, + color: AppColors.textTertiary, + ), + ), + ), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: rows[r][c], + ), + ), + ], + ), + ), + ], + ), + ), + ], + ); + } +} + +/// Plain text cell. +class Cell extends StatelessWidget { + const Cell( + this.text, { + super.key, + this.bold = false, + this.color, + this.mono = false, + }); + + final String text; + final bool bold; + final Color? color; + final bool mono; + + @override + Widget build(BuildContext context) { + return Text( + text, + overflow: TextOverflow.ellipsis, + style: mono + ? AppTypography.money(13.5, + weight: bold ? FontWeight.w700 : FontWeight.w500, color: color) + : TextStyle( + fontSize: 13.5, + fontWeight: bold ? FontWeight.w600 : FontWeight.w400, + color: color ?? AppColors.textPrimary, + ), + ); + } +} + +/// Small coloured status label. +class TagChip extends StatelessWidget { + const TagChip(this.label, {super.key, this.color = AppColors.primary}); + + final String label; + final Color color; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.sm, vertical: 3), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.12), + borderRadius: AppRadius.brPill, + ), + child: Text( + label, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: color, + ), + ), + ); + } +} + +/// Lightweight bar chart painted in code, so no charting dependency is needed. +class MiniBarChart extends StatelessWidget { + const MiniBarChart({ + super.key, + required this.values, + required this.labels, + this.height = 180, + this.color = AppColors.primary, + }); + + final List values; + final List labels; + final double height; + final Color color; + + @override + Widget build(BuildContext context) { + if (values.isEmpty) return SizedBox(height: height); + final max = values.reduce((a, b) => a > b ? a : b); + + return SizedBox( + height: height, + child: LayoutBuilder( + builder: (context, constraints) { + // Labels are dropped rather than squeezed when space is tight. + final showLabels = constraints.maxWidth / values.length >= 28; + + return Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + for (var i = 0; i < values.length; i++) + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 3), + child: Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Expanded( + child: FractionallySizedBox( + alignment: Alignment.bottomCenter, + heightFactor: + max <= 0 ? 0 : (values[i] / max).clamp(0.03, 1), + child: Container( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + color, + color.withValues(alpha: 0.45), + ], + ), + borderRadius: const BorderRadius.vertical( + top: Radius.circular(5), + ), + ), + ), + ), + ), + if (showLabels) ...[ + const SizedBox(height: AppSpacing.sm), + Text( + labels[i], + maxLines: 1, + overflow: TextOverflow.clip, + style: const TextStyle( + fontSize: 10.5, + color: AppColors.textTertiary, + ), + ), + ], + ], + ), + ), + ), + ], + ); + }, + ), + ); + } +} + +/// Horizontal proportion bar used for breakdowns. +class ProgressRow extends StatelessWidget { + const ProgressRow({ + super.key, + required this.label, + required this.value, + required this.fraction, + this.color = AppColors.primary, + }); + + final String label; + final String value; + final double fraction; + final Color color; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.sm), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Text( + label, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 13), + ), + ), + const SizedBox(width: AppSpacing.sm), + Text(value, style: AppTypography.money(13)), + ], + ), + const SizedBox(height: AppSpacing.sm), + ClipRRect( + borderRadius: AppRadius.brPill, + child: LinearProgressIndicator( + value: fraction.clamp(0, 1), + minHeight: 6, + backgroundColor: AppColors.divider, + valueColor: AlwaysStoppedAnimation(color), + ), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/payment/providers/payment_controller.dart b/lib/presentation/payment/providers/payment_controller.dart new file mode 100644 index 0000000..9fe2638 --- /dev/null +++ b/lib/presentation/payment/providers/payment_controller.dart @@ -0,0 +1,187 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../app/providers.dart'; +import '../../../core/utils/extensions.dart'; +import '../../../domain/entities/transaction.dart'; +import '../../../domain/usecases/checkout_sale.dart'; +import '../../pos/providers/cart_controller.dart'; +import '../../pos/providers/catalog_providers.dart'; + +/// UI state for the payment screen. +class PaymentState { + const PaymentState({ + this.splits = const [], + this.activeMethod = PaymentMethod.cash, + this.cashTendered = 0, + this.reference = '', + this.isProcessing = false, + this.error, + this.result, + }); + + final List splits; + final PaymentMethod activeMethod; + final double cashTendered; + final String reference; + final bool isProcessing; + final String? error; + final CheckoutResult? result; + + double get settled => + splits.fold(0.0, (sum, s) => sum + s.amount).asMoney; + + bool get isComplete => result != null; + + PaymentState copyWith({ + List? splits, + PaymentMethod? activeMethod, + double? cashTendered, + String? reference, + bool? isProcessing, + String? error, + bool clearError = false, + CheckoutResult? result, + }) { + return PaymentState( + splits: splits ?? this.splits, + activeMethod: activeMethod ?? this.activeMethod, + cashTendered: cashTendered ?? this.cashTendered, + reference: reference ?? this.reference, + isProcessing: isProcessing ?? this.isProcessing, + error: clearError ? null : (error ?? this.error), + result: result ?? this.result, + ); + } +} + +class PaymentController extends StateNotifier { + PaymentController(this._ref) : super(const PaymentState()); + + final Ref _ref; + + double get _billTotal => _ref.read(cartControllerProvider).grandTotal; + + /// Amount still outstanding after the tenders recorded so far. + double get balanceDue => + (_billTotal - state.settled).clamp(0, double.infinity); + + double get changeDue { + if (!state.activeMethod.needsChange) return 0; + final diff = state.cashTendered - balanceDue; + return diff > 0 ? diff.asMoney : 0; + } + + bool get canConfirm { + if (state.activeMethod.needsChange) { + return state.cashTendered >= balanceDue && balanceDue > 0; + } + return balanceDue > 0; + } + + void selectMethod(PaymentMethod method) { + state = state.copyWith( + activeMethod: method, + cashTendered: 0, + reference: '', + clearError: true, + ); + } + + void setCashTendered(double amount) => + state = state.copyWith(cashTendered: amount, clearError: true); + + /// Adds to the tendered amount — powers the quick-cash denomination chips. + void addCash(double amount) => setCashTendered(state.cashTendered + amount); + + /// Fills the exact balance, the most common cash case. + void tenderExact() => setCashTendered(balanceDue); + + void setReference(String value) => + state = state.copyWith(reference: value, clearError: true); + + /// Records the active tender. For a split payment, call this once per part. + void addSplit({double? amount}) { + final value = (amount ?? balanceDue).clamp(0, balanceDue).toDouble(); + if (value <= 0) return; + + final split = PaymentSplit( + method: state.activeMethod, + amount: value.asMoney, + tendered: state.activeMethod.needsChange + ? (state.cashTendered > 0 ? state.cashTendered : value) + : null, + reference: state.reference.trim().isEmpty ? null : state.reference.trim(), + ); + + state = state.copyWith( + splits: [...state.splits, split], + cashTendered: 0, + reference: '', + clearError: true, + ); + } + + void removeSplit(int index) { + final next = [...state.splits]..removeAt(index); + state = state.copyWith(splits: next); + } + + void clearSplits() => state = state.copyWith(splits: const []); + + /// Finalises the sale. On success the caller navigates to the receipt. + Future confirm() async { + if (state.isProcessing) return null; + + // A single-tender sale needn't be staged first — fold it in automatically. + var splits = state.splits; + if (splits.isEmpty || balanceDue > 0.01) { + addSplit(); + splits = state.splits; + } + + state = state.copyWith(isProcessing: true, clearError: true); + + try { + final cart = _ref.read(cartControllerProvider); + final session = _ref.read(cashierSessionProvider); + + final result = await _ref.read(checkoutSaleProvider)( + cart: cart, + payments: splits, + cashierName: session.name, + ); + + state = state.copyWith(isProcessing: false, result: result); + + // Fire and forget — printing must never block the next sale. + final receipts = _ref.read(receiptServiceProvider); + unawaited(receipts.printDirect(result.transaction)); + unawaited(receipts.openCashDrawer()); + unawaited(_ref.read(soundServiceProvider).saleComplete()); + + // Stock changed, so the grid must refresh. + _ref.invalidate(allProductsProvider); + _ref.invalidate(visibleProductsProvider); + + return result; + } on CheckoutFailure catch (e) { + state = state.copyWith(isProcessing: false, error: e.message); + return null; + } catch (e) { + state = state.copyWith( + isProcessing: false, + error: 'Could not complete the sale. $e', + ); + return null; + } + } + + void reset() => state = const PaymentState(); +} + +final paymentControllerProvider = + StateNotifierProvider.autoDispose( + (ref) => PaymentController(ref), +); diff --git a/lib/presentation/payment/screens/payment_screen.dart b/lib/presentation/payment/screens/payment_screen.dart new file mode 100644 index 0000000..ece1e8d --- /dev/null +++ b/lib/presentation/payment/screens/payment_screen.dart @@ -0,0 +1,511 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_animate/flutter_animate.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/extensions.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/widgets/glass_card.dart'; +import '../../../core/widgets/numeric_keypad.dart'; +import '../../../core/widgets/primary_button.dart'; +import '../../../domain/entities/transaction.dart'; +import '../../pos/providers/cart_controller.dart'; +import '../providers/payment_controller.dart'; + +class PaymentScreen extends ConsumerStatefulWidget { + const PaymentScreen({super.key}); + + @override + ConsumerState createState() => _PaymentScreenState(); +} + +class _PaymentScreenState extends ConsumerState { + String _cashBuffer = ''; + + void _syncCash() { + final value = double.tryParse(_cashBuffer) ?? 0; + ref.read(paymentControllerProvider.notifier).setCashTendered(value); + } + + void _appendCash(String d) { + if (d == '.' && _cashBuffer.contains('.')) return; + if (_cashBuffer.length >= 8) return; + setState(() => _cashBuffer += d); + _syncCash(); + } + + void _backspaceCash() { + if (_cashBuffer.isEmpty) return; + setState(() => _cashBuffer = _cashBuffer.substring(0, _cashBuffer.length - 1)); + _syncCash(); + } + + void _setCash(double value) { + setState(() => _cashBuffer = value.toStringAsFixed(0)); + _syncCash(); + } + + Future _confirm() async { + final result = await ref.read(paymentControllerProvider.notifier).confirm(); + if (result == null || !mounted) return; + + // Sale is banked — clear the terminal and show the receipt. + ref.read(cartControllerProvider.notifier).reset(); + context.go(AppRoutes.receipt, extra: result.transaction); + } + + @override + Widget build(BuildContext context) { + final cart = ref.watch(cartControllerProvider); + final state = ref.watch(paymentControllerProvider); + final controller = ref.read(paymentControllerProvider.notifier); + + return Scaffold( + backgroundColor: AppColors.background, + appBar: AppBar( + title: const Text('Payment'), + leading: IconButton( + icon: const Icon(Icons.arrow_back_rounded), + onPressed: () => context.pop(), + ), + ), + body: Padding( + padding: const EdgeInsets.all(AppSpacing.xxl), + child: context.isCompact + ? SingleChildScrollView( + child: Column(children: [ + _amountCard(controller, state), + const SizedBox(height: AppSpacing.lg), + _methodsCard(controller, state), + const SizedBox(height: AppSpacing.lg), + _tenderCard(controller, state), + ]), + ) + : Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + flex: 4, + child: Column(children: [ + _amountCard(controller, state), + const SizedBox(height: AppSpacing.lg), + Expanded(child: _methodsCard(controller, state)), + ]), + ), + const SizedBox(width: AppSpacing.lg), + Expanded(flex: 5, child: _tenderCard(controller, state)), + ], + ), + ), + bottomNavigationBar: SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB( + AppSpacing.xxl, + 0, + AppSpacing.xxl, + AppSpacing.xxl, + ), + child: Column(mainAxisSize: MainAxisSize.min, children: [ + if (state.error != null) ...[ + Container( + width: double.infinity, + padding: const EdgeInsets.all(AppSpacing.md), + margin: const EdgeInsets.only(bottom: AppSpacing.md), + decoration: BoxDecoration( + color: AppColors.dangerSurface, + borderRadius: AppRadius.brSm, + ), + child: Row(children: [ + const Icon(Icons.error_outline_rounded, + color: AppColors.danger, size: 18), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Text(state.error!, + style: const TextStyle(color: AppColors.danger)), + ), + ]), + ).animate().shake(duration: 300.ms, hz: 3), + ], + PrimaryButton( + label: 'Complete Sale', + icon: Icons.check_circle_outline_rounded, + large: true, + tone: ButtonTone.success, + busy: state.isProcessing, + onPressed: cart.isEmpty ? null : _confirm, + trailing: Text( + Formatters.money(cart.grandTotal), + style: AppTypography.money(21, color: Colors.white), + ), + ), + ]), + ), + ), + ); + } + + // ------------------------------------------------------------- Sections + Widget _amountCard(PaymentController controller, PaymentState state) { + final cart = ref.watch(cartControllerProvider); + + return GlassCard( + padding: const EdgeInsets.all(AppSpacing.xxl), + radius: AppRadius.xl, + tinted: true, + child: Column(children: [ + Text('Amount due', style: context.text.labelMedium), + const SizedBox(height: AppSpacing.xs), + Text( + Formatters.money(controller.balanceDue), + style: AppTypography.money(40, color: AppColors.primary), + ), + const SizedBox(height: AppSpacing.md), + Row(mainAxisAlignment: MainAxisAlignment.center, children: [ + _mini('Items', '${cart.lineCount}'), + _dot(), + _mini('Bill total', Formatters.money(cart.grandTotal)), + if (state.settled > 0) ...[ + _dot(), + _mini('Settled', Formatters.money(state.settled)), + ], + ]), + ]), + ); + } + + Widget _methodsCard(PaymentController controller, PaymentState state) { + return GlassCard( + padding: const EdgeInsets.all(AppSpacing.xl), + radius: AppRadius.xl, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text('Payment method', style: context.text.titleMedium), + const SizedBox(height: AppSpacing.lg), + Wrap( + spacing: AppSpacing.md, + runSpacing: AppSpacing.md, + children: PaymentMethod.values + .where((m) => m != PaymentMethod.loyalty) + .map((m) => _MethodTile( + method: m, + selected: state.activeMethod == m, + onTap: () { + setState(() => _cashBuffer = ''); + controller.selectMethod(m); + }, + )) + .toList(), + ), + + if (state.splits.isNotEmpty) ...[ + const SizedBox(height: AppSpacing.xl), + const Divider(), + const SizedBox(height: AppSpacing.md), + Row(children: [ + Text('Split tenders', style: context.text.titleSmall), + const Spacer(), + TextButton( + onPressed: controller.clearSplits, + style: TextButton.styleFrom( + foregroundColor: AppColors.danger), + child: const Text('Clear all'), + ), + ]), + const SizedBox(height: AppSpacing.sm), + ...state.splits.asMap().entries.map((e) => Padding( + padding: const EdgeInsets.only(bottom: AppSpacing.sm), + child: Row(children: [ + Text(e.value.method.emoji, + style: const TextStyle(fontSize: 16)), + const SizedBox(width: AppSpacing.sm), + Expanded(child: Text(e.value.method.label)), + Text(Formatters.money(e.value.amount), + style: AppTypography.money(14.5)), + IconButton( + onPressed: () => controller.removeSplit(e.key), + icon: const Icon(Icons.close_rounded, size: 17), + color: AppColors.textTertiary, + constraints: + const BoxConstraints(minWidth: 30, minHeight: 30), + padding: EdgeInsets.zero, + ), + ]), + )), + ], + ], + ), + ); + } + + Widget _tenderCard(PaymentController controller, PaymentState state) { + final isCash = state.activeMethod.needsChange; + + return GlassCard( + padding: const EdgeInsets.all(AppSpacing.xl), + radius: AppRadius.xl, + child: isCash + ? _cashTender(controller, state) + : _referenceTender(controller, state), + ); + } + + Widget _cashTender(PaymentController controller, PaymentState state) { + final change = controller.changeDue; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text('Cash received', style: context.text.titleMedium), + const SizedBox(height: AppSpacing.md), + + Container( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.xl, + vertical: AppSpacing.lg, + ), + decoration: BoxDecoration( + color: AppColors.surfaceAlt, + borderRadius: AppRadius.brLg, + border: Border.all(color: AppColors.border), + ), + child: Row(children: [ + const Text('₹', + style: TextStyle(fontSize: 24, color: AppColors.textTertiary)), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Text( + _cashBuffer.isEmpty ? '0' : _cashBuffer, + style: AppTypography.money(30), + ), + ), + ]), + ), + + const SizedBox(height: AppSpacing.md), + Wrap( + spacing: AppSpacing.sm, + runSpacing: AppSpacing.sm, + children: [ + ActionChip( + avatar: const Icon(Icons.done_all_rounded, size: 15), + label: const Text('Exact'), + onPressed: () => _setCash(controller.balanceDue), + ), + ...[50, 100, 200, 500, 2000].map( + (note) => ActionChip( + label: Text('₹$note'), + onPressed: () => _setCash( + (double.tryParse(_cashBuffer) ?? 0) + note, + ), + ), + ), + ], + ), + + const SizedBox(height: AppSpacing.lg), + + AnimatedContainer( + duration: AppMotion.normal, + padding: const EdgeInsets.all(AppSpacing.lg), + decoration: BoxDecoration( + color: change > 0 + ? AppColors.successSurface + : AppColors.surfaceAlt, + borderRadius: AppRadius.brMd, + ), + child: Row(children: [ + Icon( + change > 0 + ? Icons.currency_exchange_rounded + : Icons.info_outline_rounded, + size: 19, + color: change > 0 ? AppColors.success : AppColors.textTertiary, + ), + const SizedBox(width: AppSpacing.md), + Text( + 'Change to return', + style: TextStyle( + fontWeight: FontWeight.w600, + color: change > 0 + ? AppColors.success + : AppColors.textSecondary, + ), + ), + const Spacer(), + Text( + Formatters.money(change), + style: AppTypography.money( + 22, + color: change > 0 ? AppColors.success : AppColors.textTertiary, + ), + ), + ]), + ), + + const SizedBox(height: AppSpacing.lg), + Center( + child: NumericKeypad( + allowDecimal: true, + maxWidth: 330, + onKey: _appendCash, + onBackspace: _backspaceCash, + ), + ), + + const SizedBox(height: AppSpacing.md), + OutlinedButton.icon( + onPressed: controller.balanceDue > 0 + ? () { + controller.addSplit( + amount: (double.tryParse(_cashBuffer) ?? 0) + .clamp(0, controller.balanceDue) + .toDouble(), + ); + setState(() => _cashBuffer = ''); + } + : null, + icon: const Icon(Icons.call_split_rounded, size: 17), + label: const Text('Add as split payment'), + ), + ], + ); + } + + Widget _referenceTender(PaymentController controller, PaymentState state) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row(children: [ + Text(state.activeMethod.emoji, style: const TextStyle(fontSize: 22)), + const SizedBox(width: AppSpacing.sm), + Text('${state.activeMethod.label} payment', + style: context.text.titleMedium), + ]), + const SizedBox(height: AppSpacing.xxl), + + Center( + child: Column(children: [ + Container( + width: 120, + height: 120, + decoration: BoxDecoration( + color: AppColors.primarySurface, + borderRadius: AppRadius.brXl, + ), + alignment: Alignment.center, + child: Text(state.activeMethod.emoji, + style: const TextStyle(fontSize: 52)), + ), + const SizedBox(height: AppSpacing.lg), + Text( + 'Charge ${Formatters.money(controller.balanceDue)} ' + 'on the ${state.activeMethod.label.toLowerCase()} terminal', + textAlign: TextAlign.center, + style: context.text.bodyMedium, + ), + ]), + ), + + const SizedBox(height: AppSpacing.xxl), + if (state.activeMethod.needsReference) + TextField( + onChanged: controller.setReference, + decoration: InputDecoration( + labelText: switch (state.activeMethod) { + PaymentMethod.card => 'Approval code', + PaymentMethod.upi => 'UPI transaction ID', + PaymentMethod.giftCard => 'Gift card number', + _ => 'Reference', + }, + prefixIcon: const Icon(Icons.tag_rounded), + ), + ), + + const SizedBox(height: AppSpacing.xxxl), + OutlinedButton.icon( + onPressed: controller.balanceDue > 0 + ? () => controller.addSplit() + : null, + icon: const Icon(Icons.call_split_rounded, size: 17), + label: const Text('Add as split payment'), + ), + ], + ); + } + + Widget _mini(String label, String value) => Column(children: [ + Text(label, + style: const TextStyle( + fontSize: 11, + color: AppColors.textSecondary, + )), + Text(value, + style: AppTypography.money(14, weight: FontWeight.w600)), + ]); + + Widget _dot() => Container( + width: 3, + height: 3, + margin: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), + decoration: const BoxDecoration( + color: AppColors.textTertiary, + shape: BoxShape.circle, + ), + ); +} + +class _MethodTile extends StatelessWidget { + const _MethodTile({ + required this.method, + required this.selected, + required this.onTap, + }); + + final PaymentMethod method; + final bool selected; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return Material( + color: selected ? AppColors.primary : AppColors.surfaceAlt, + borderRadius: AppRadius.brMd, + child: InkWell( + onTap: onTap, + borderRadius: AppRadius.brMd, + child: AnimatedContainer( + duration: AppMotion.fast, + width: 118, + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.md, + vertical: AppSpacing.lg, + ), + decoration: BoxDecoration( + borderRadius: AppRadius.brMd, + border: Border.all( + color: selected ? AppColors.primary : AppColors.border, + ), + ), + child: Column(children: [ + Text(method.emoji, style: const TextStyle(fontSize: 24)), + const SizedBox(height: AppSpacing.sm), + Text( + method.label, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: selected ? Colors.white : AppColors.textPrimary, + ), + ), + ]), + ), + ), + ); + } +} diff --git a/lib/presentation/pos/providers/cart_controller.dart b/lib/presentation/pos/providers/cart_controller.dart new file mode 100644 index 0000000..e0e54fa --- /dev/null +++ b/lib/presentation/pos/providers/cart_controller.dart @@ -0,0 +1,307 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:uuid/uuid.dart'; + +import '../../../app/providers.dart'; +import '../../../core/constants/app_constants.dart'; +import '../../../core/services/sound_service.dart'; +import '../../../domain/entities/cart.dart'; +import '../../../domain/entities/customer.dart'; +import '../../../domain/entities/product.dart'; +import '../../../domain/entities/transaction.dart'; +import '../../../domain/repositories/product_repository.dart'; +import '../../../domain/repositories/transaction_repository.dart'; + +/// Transient feedback for the scan toast — never a blocking dialog. +enum ScanOutcome { added, incremented, notFound, outOfStock } + +class ScanFeedback { + const ScanFeedback({ + required this.outcome, + required this.stamp, + this.product, + this.message, + }); + + final ScanOutcome outcome; + final DateTime stamp; + final Product? product; + final String? message; + + bool get isSuccess => + outcome == ScanOutcome.added || outcome == ScanOutcome.incremented; +} + +/// Owns the live bill. +/// +/// All mutations funnel through here so that scanner input, product taps and +/// keyboard shortcuts share one code path and one set of guarantees. +class CartController extends StateNotifier { + CartController({ + required ProductRepository products, + required TransactionRepository transactions, + required SoundService sound, + required this.onFeedback, + }) : _products = products, + _transactions = transactions, + _sound = sound, + super(Cart.empty); + + final ProductRepository _products; + final TransactionRepository _transactions; + final SoundService _sound; + final void Function(ScanFeedback) onFeedback; + + static const _uuid = Uuid(); + + /// Snapshots for undo — capped so memory can't grow unbounded on a terminal + /// that runs for days. + final List _undoStack = []; + static const int _maxUndo = 25; + + bool get canUndo => _undoStack.isNotEmpty; + + void _push() { + _undoStack.add(state); + if (_undoStack.length > _maxUndo) _undoStack.removeAt(0); + } + + void undo() { + if (_undoStack.isEmpty) return; + state = _undoStack.removeLast(); + } + + // ------------------------------------------------------------ Line items + /// Adds a product, merging into the existing line when already present. + void addProduct(Product product, {double quantity = 1}) { + if (product.isOutOfStock) { + _sound.scanError(); + onFeedback(ScanFeedback( + outcome: ScanOutcome.outOfStock, + stamp: DateTime.now(), + product: product, + message: '${product.name} is out of stock', + )); + return; + } + + _push(); + + final existing = state.lineFor(product.id); + final requested = (existing?.quantity ?? 0) + quantity; + + if (requested > product.stock) { + _undoStack.removeLast(); + _sound.scanError(); + onFeedback(ScanFeedback( + outcome: ScanOutcome.outOfStock, + stamp: DateTime.now(), + product: product, + message: 'Only ${product.stock.toStringAsFixed(0)} ' + '${product.unit.symbol} left', + )); + return; + } + + if (existing == null) { + state = state.copyWith(lines: [ + ...state.lines, + CartLine( + product: product, + quantity: quantity, + addedAt: DateTime.now(), + ), + ]); + } else { + state = state.copyWith( + lines: _replace(existing.copyWith(quantity: requested)), + ); + } + + _clampRedemption(); + _sound.scanSuccess(); + onFeedback(ScanFeedback( + outcome: existing == null ? ScanOutcome.added : ScanOutcome.incremented, + stamp: DateTime.now(), + product: product, + )); + } + + /// Scanner entry point. Resolves the barcode and adds it with no dialogs. + Future scanBarcode(String code) async { + final product = await _products.findByBarcode(code); + + if (product == null) { + _sound.scanError(); + onFeedback(ScanFeedback( + outcome: ScanOutcome.notFound, + stamp: DateTime.now(), + message: 'No product for barcode $code', + )); + return; + } + + addProduct(product); + } + + void setQuantity(String productId, double quantity) { + final line = state.lineFor(productId); + if (line == null) return; + + if (quantity <= 0) { + removeLine(productId); + return; + } + + final capped = quantity + .clamp(0, AppConstants.maxCartQuantityPerLine.toDouble()) + .toDouble(); + + if (capped > line.product.stock) { + _sound.scanError(); + onFeedback(ScanFeedback( + outcome: ScanOutcome.outOfStock, + stamp: DateTime.now(), + product: line.product, + message: 'Only ${line.product.stock.toStringAsFixed(0)} in stock', + )); + return; + } + + _push(); + state = state.copyWith(lines: _replace(line.copyWith(quantity: capped))); + _clampRedemption(); + } + + void increment(String productId, {double by = 1}) { + final line = state.lineFor(productId); + if (line == null) return; + setQuantity(productId, line.quantity + by); + } + + void decrement(String productId, {double by = 1}) { + final line = state.lineFor(productId); + if (line == null) return; + setQuantity(productId, line.quantity - by); + } + + void removeLine(String productId) { + if (!state.contains(productId)) return; + _push(); + state = state.copyWith( + lines: state.lines.where((l) => l.product.id != productId).toList(), + ); + _clampRedemption(); + } + + void applyLineDiscount(String productId, Discount discount) { + final line = state.lineFor(productId); + if (line == null) return; + _push(); + state = state.copyWith(lines: _replace(line.copyWith(discount: discount))); + _clampRedemption(); + } + + // ------------------------------------------------------------ Bill level + void applyBillDiscount(Discount discount) { + _push(); + state = state.copyWith(billDiscount: discount); + _clampRedemption(); + } + + void clearBillDiscount() => applyBillDiscount(Discount.none); + + void attachCustomer(Customer? customer) { + _push(); + state = customer == null + ? state.copyWith(clearCustomer: true, pointsRedeemed: 0) + : state.copyWith(customer: customer); + _clampRedemption(); + } + + void redeemPoints(int points) { + final max = state.maxRedeemablePoints; + _push(); + state = state.copyWith(pointsRedeemed: points.clamp(0, max)); + } + + void redeemAllPoints() => redeemPoints(state.maxRedeemablePoints); + + void clearRedemption() => redeemPoints(0); + + void setNote(String? note) => state = state.copyWith(note: note); + + /// Keeps redemption legal after the bill shrinks below the redeemed value. + void _clampRedemption() { + if (state.pointsRedeemed == 0) return; + final max = state.maxRedeemablePoints; + if (state.pointsRedeemed > max) { + state = state.copyWith(pointsRedeemed: max); + } + } + + // --------------------------------------------------------------- Session + void clear() { + _push(); + state = Cart.empty; + } + + /// Starts a brand new sale, dropping undo history and the customer. + void reset() { + _undoStack.clear(); + state = Cart.empty; + } + + /// Keeps the customer attached for a follow-up bill. + void resetKeepingCustomer() { + _undoStack.clear(); + state = Cart(customer: state.customer); + } + + // ---------------------------------------------------------- Parked bills + Future park({String? label}) async { + if (state.isEmpty) return; + await _transactions.park(ParkedBill( + id: _uuid.v4(), + cart: state, + parkedAt: DateTime.now(), + label: label, + )); + reset(); + } + + Future resume(ParkedBill bill) async { + await _transactions.removeParked(bill.id); + _undoStack.clear(); + state = bill.cart; + } + + List _replace(CartLine updated) => [ + for (final l in state.lines) + if (l.product.id == updated.product.id) updated else l, + ]; +} + +// ----------------------------------------------------------------- Providers +final scanFeedbackProvider = StateProvider((ref) => null); + +final cartControllerProvider = + StateNotifierProvider((ref) { + return CartController( + products: ref.watch(productRepositoryProvider), + transactions: ref.watch(transactionRepositoryProvider), + sound: ref.watch(soundServiceProvider), + onFeedback: (feedback) => + ref.read(scanFeedbackProvider.notifier).state = feedback, + ); +}); + +/// Convenience selectors — each rebuilds only the widget that needs it. +final cartTotalProvider = + Provider((ref) => ref.watch(cartControllerProvider).grandTotal); + +final cartItemCountProvider = + Provider((ref) => ref.watch(cartControllerProvider).lineCount); + +final parkedBillsProvider = FutureProvider>( + (ref) => ref.watch(transactionRepositoryProvider).parkedBills(), +); diff --git a/lib/presentation/pos/providers/catalog_providers.dart b/lib/presentation/pos/providers/catalog_providers.dart new file mode 100644 index 0000000..3a2c06b --- /dev/null +++ b/lib/presentation/pos/providers/catalog_providers.dart @@ -0,0 +1,44 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../app/providers.dart'; +import '../../../domain/entities/product.dart'; + +/// `null` means the "All" chip is selected. +final selectedCategoryProvider = + StateProvider((ref) => null); + +final searchQueryProvider = StateProvider((ref) => ''); + +final allProductsProvider = FutureProvider>( + (ref) => ref.watch(productRepositoryProvider).getAll(), +); + +/// The grid's data source: category filter and search applied together. +final visibleProductsProvider = FutureProvider>((ref) async { + final repo = ref.watch(productRepositoryProvider); + final query = ref.watch(searchQueryProvider); + final category = ref.watch(selectedCategoryProvider); + + final base = query.trim().isEmpty + ? await repo.getAll() + : await repo.search(query); + + if (category == null) return base; + return base.where((p) => p.category == category).toList(); +}); + +/// Counts per category for the chip badges. +final categoryCountsProvider = + FutureProvider>((ref) async { + final products = await ref.watch(allProductsProvider.future); + final map = {}; + for (final p in products) { + map[p.category] = (map[p.category] ?? 0) + 1; + } + return map; +}); + +final lowStockProductsProvider = FutureProvider>((ref) async { + final products = await ref.watch(allProductsProvider.future); + return products.where((p) => p.isLowStock || p.isOutOfStock).toList(); +}); diff --git a/lib/presentation/pos/providers/navigation_provider.dart b/lib/presentation/pos/providers/navigation_provider.dart new file mode 100644 index 0000000..536c458 --- /dev/null +++ b/lib/presentation/pos/providers/navigation_provider.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +/// The modules a cashier needs. Deliberately excludes analytics — this +/// terminal is for billing, not back-office reporting. +enum PosModule { + pos('Point of Sale', 'POS', Icons.point_of_sale_rounded, NavSection.billing), + customers('Customers', 'Customers', Icons.people_alt_rounded, + NavSection.billing), + + productImport('Product Import', 'Product Import', + Icons.cloud_download_rounded, NavSection.catalogue), + promos('Promotions', 'Promo', Icons.sell_rounded, NavSection.catalogue), + + events('Events', 'Events', Icons.sync_rounded, NavSection.session), + settings('Settings', 'Settings', Icons.settings_rounded, NavSection.session); + + const PosModule(this.title, this.label, this.icon, this.section); + + /// Long form, shown in the page header. + final String title; + + /// Short form, shown in the sidebar. + final String label; + + final IconData icon; + final NavSection section; +} + +/// Groups the navigation into labelled blocks. +enum NavSection { + billing('Billing'), + catalogue('Catalogue'), + session('Session'); + + const NavSection(this.label); + + final String label; + + List get modules => + PosModule.values.where((m) => m.section == this).toList(); +} + +final activeModuleProvider = StateProvider((ref) => PosModule.pos); diff --git a/lib/presentation/pos/screens/pos_dashboard_screen.dart b/lib/presentation/pos/screens/pos_dashboard_screen.dart new file mode 100644 index 0000000..21f3289 --- /dev/null +++ b/lib/presentation/pos/screens/pos_dashboard_screen.dart @@ -0,0 +1,171 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/services/barcode_service.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_layout.dart'; +import '../../modules/screens/customers_view.dart'; +import '../../modules/screens/events_view.dart'; +import '../../modules/screens/product_import_view.dart'; +import '../../modules/screens/promos_view.dart'; +import '../../modules/screens/settings_view.dart'; +import '../../sync/providers/sync_controller.dart'; +import '../providers/cart_controller.dart'; +import '../providers/navigation_provider.dart'; +import '../widgets/app_sidebar.dart'; +import '../widgets/billing_panel.dart'; +import '../widgets/cart_fab.dart'; +import '../widgets/page_header.dart'; +import 'pos_view.dart'; + +/// Application shell. +/// +/// Owns the sidebar, page header and the body for whichever module is active. +/// Keeping one shell means navigation never rebuilds the chrome, and the +/// scanner stays live across modules. +/// +/// Layout collapses in a fixed order as width shrinks: +/// +/// * `>= 1300` sidebar with labels, docked bill +/// * `1120–1300` sidebar as an icon rail, docked bill +/// * `920–1120` icon rail, bill becomes a bottom sheet +/// * `< 920` sidebar goes off-canvas behind a menu button +class PosDashboardScreen extends ConsumerStatefulWidget { + const PosDashboardScreen({super.key}); + + @override + ConsumerState createState() => _PosDashboardScreenState(); +} + +class _PosDashboardScreenState extends ConsumerState { + final GlobalKey _scaffoldKey = GlobalKey(); + final FocusNode _searchFocus = FocusNode(); + late final BarcodeService _barcode; + + @override + void initState() { + super.initState(); + + // The scanner behaves like a keyboard, so listen globally rather than + // depending on any one field holding focus. A scan from another module + // jumps back to billing, which is what a cashier expects. + _barcode = BarcodeService( + onScan: (code) { + // Without an imported catalogue there is nothing to resolve against. + if (!ref.read(catalogueReadyProvider)) return; + ref.read(activeModuleProvider.notifier).state = PosModule.pos; + ref.read(cartControllerProvider.notifier).scanBarcode(code); + }, + )..attach(); + } + + @override + void dispose() { + _barcode.dispose(); + _searchFocus.dispose(); + super.dispose(); + } + + void _openBillingSheet() { + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (_) => FractionallySizedBox( + heightFactor: 0.92, + child: ClipRRect( + borderRadius: const BorderRadius.vertical( + top: Radius.circular(AppRadius.xxl), + ), + child: const BillingPanel(inSheet: true), + ), + ), + ); + } + + Widget _body(PosModule module, PosLayout layout) => switch (module) { + PosModule.pos => PosView(layout: layout, searchFocus: _searchFocus), + PosModule.customers => const CustomersView(), + PosModule.productImport => const ProductImportView(), + PosModule.promos => const PromosView(), + PosModule.events => const EventsView(), + PosModule.settings => const SettingsView(), + }; + + @override + Widget build(BuildContext context) { + final layout = PosLayout.of(context); + final module = ref.watch(activeModuleProvider); + final ready = ref.watch(catalogueReadyProvider); + final isPos = module == PosModule.pos && ready; + + // Only the terminal itself needs the bill docked beside it. + final showDockedBill = isPos && !layout.billingIsSheet; + final showCartFab = isPos && layout.billingIsSheet; + + return Scaffold( + key: _scaffoldKey, + backgroundColor: AppColors.background, + drawer: layout.sidebarIsDrawer + ? Drawer( + width: PosLayout.expandedWidth, + backgroundColor: AppColors.surface, + child: AppSidebar( + mode: SidebarMode.expanded, + onDestinationTap: () => Navigator.of(context).maybePop(), + ), + ) + : null, + floatingActionButton: + showCartFab ? CartFab(onTap: _openBillingSheet) : null, + floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, + body: CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.f2): + _searchFocus.requestFocus, + const SingleActivator(LogicalKeyboardKey.f8): () => + ref.read(cartControllerProvider.notifier).undo(), + const SingleActivator(LogicalKeyboardKey.escape): + _searchFocus.unfocus, + }, + child: Focus( + autofocus: true, + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (!layout.sidebarIsDrawer) AppSidebar(mode: layout.sidebar), + Expanded( + child: Column( + children: [ + PageHeader( + layout: layout, + onMenuTap: () => _scaffoldKey.currentState?.openDrawer(), + ), + Expanded( + child: AnimatedSwitcher( + duration: AppMotion.fast, + child: KeyedSubtree( + key: ValueKey(module), + child: _body(module, layout), + ), + ), + ), + ], + ), + ), + if (showDockedBill) ...[ + const VerticalDivider(width: 1), + SizedBox( + width: layout.billingWidth, + child: const BillingPanel(), + ), + ], + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/pos/screens/pos_view.dart b/lib/presentation/pos/screens/pos_view.dart new file mode 100644 index 0000000..bfa1192 --- /dev/null +++ b/lib/presentation/pos/screens/pos_view.dart @@ -0,0 +1,197 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_layout.dart'; +import '../../../core/widgets/primary_button.dart'; +import '../../sync/providers/sync_controller.dart'; +import '../providers/navigation_provider.dart'; +import '../widgets/category_chips.dart'; +import '../widgets/customer_bar.dart'; +import '../widgets/product_grid.dart'; +import '../widgets/scan_toast.dart'; +import '../widgets/search_field.dart'; + +/// Catalogue half of the terminal. +/// +/// Gated on the catalogue import: with no products loaded there is nothing to +/// sell, so the cashier is sent to the import step instead of a broken grid. +class PosView extends ConsumerWidget { + const PosView({super.key, required this.layout, required this.searchFocus}); + + final PosLayout layout; + final FocusNode searchFocus; + + @override + Widget build(BuildContext context, WidgetRef ref) { + if (!ref.watch(catalogueReadyProvider)) { + return const _CatalogueRequired(); + } + + final pad = layout.contentPadding; + + // Keep the last grid row clear of the floating bill button. + final bottomInset = layout.billingIsSheet + ? AppSizes.buttonHeightLarge + AppSpacing.xxxl + : AppSpacing.xxl; + + return Stack( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const CustomerBar(), + const Divider(height: 1), + Padding( + padding: + EdgeInsets.fromLTRB(pad, AppSpacing.lg, pad, AppSpacing.md), + child: PosSearchField(focusNode: searchFocus), + ), + CategoryChips(horizontalPadding: pad), + const SizedBox(height: AppSpacing.md), + Expanded( + child: ProductGrid( + horizontalPadding: pad, + tileExtent: layout.gridTileExtent, + bottomPadding: bottomInset, + ), + ), + ], + ), + Positioned( + left: 0, + right: 0, + bottom: bottomInset, + child: const Align( + alignment: Alignment.bottomCenter, + child: ScanToast(), + ), + ), + ], + ); + } +} + +/// Shown until the catalogue has been pulled onto this terminal. +class _CatalogueRequired extends ConsumerWidget { + const _CatalogueRequired(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final state = ref.watch(catalogueImportProvider); + final running = state is ImportRunning; + + return Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(AppSpacing.xxl), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 460), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 96, + height: 96, + decoration: const BoxDecoration( + color: AppColors.primarySurface, + shape: BoxShape.circle, + ), + child: const Icon(Icons.cloud_download_outlined, + size: 42, color: AppColors.primary), + ), + const SizedBox(height: AppSpacing.xxl), + Text( + 'Import products to start billing', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineSmall, + ), + const SizedBox(height: AppSpacing.sm), + const Text( + 'This terminal has no catalogue yet. Pull the current products ' + 'once at the start of your shift — after that everything runs ' + 'offline.', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 14, + color: AppColors.textSecondary, + height: 1.6, + ), + ), + const SizedBox(height: AppSpacing.xxl), + + if (running) ...[ + Text( + state.stage, + style: const TextStyle( + fontSize: 13, + color: AppColors.textSecondary, + ), + ), + const SizedBox(height: AppSpacing.sm), + ClipRRect( + borderRadius: AppRadius.brPill, + child: LinearProgressIndicator( + value: state.progress, + minHeight: 8, + backgroundColor: AppColors.divider, + valueColor: const AlwaysStoppedAnimation( + AppColors.primary), + ), + ), + const SizedBox(height: AppSpacing.lg), + ], + + if (state is ImportFailed) ...[ + Container( + padding: const EdgeInsets.all(AppSpacing.md), + margin: const EdgeInsets.only(bottom: AppSpacing.lg), + decoration: BoxDecoration( + color: AppColors.dangerSurface, + borderRadius: AppRadius.brSm, + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon(Icons.wifi_off_rounded, + color: AppColors.danger, size: 18), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Text( + state.message, + style: const TextStyle( + color: AppColors.danger, + fontSize: 13, + height: 1.45, + ), + ), + ), + ], + ), + ), + ], + + PrimaryButton( + label: 'Import catalogue now', + icon: Icons.cloud_download_rounded, + large: true, + busy: running, + onPressed: running + ? null + : () => ref.read(catalogueImportProvider.notifier).run(), + ), + const SizedBox(height: AppSpacing.md), + TextButton.icon( + onPressed: () => ref + .read(activeModuleProvider.notifier) + .state = PosModule.productImport, + icon: const Icon(Icons.open_in_new_rounded, size: 16), + label: const Text('Open Product Import'), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/pos/widgets/app_sidebar.dart b/lib/presentation/pos/widgets/app_sidebar.dart new file mode 100644 index 0000000..17f5ce2 --- /dev/null +++ b/lib/presentation/pos/widgets/app_sidebar.dart @@ -0,0 +1,485 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../app/providers.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_layout.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../domain/entities/sync_event.dart'; +import '../../auth/providers/auth_controller.dart'; +import '../../sync/widgets/sign_out_dialog.dart'; +import '../providers/cart_controller.dart'; +import '../../sync/providers/sync_controller.dart'; +import '../providers/navigation_provider.dart'; + +/// Left navigation rail. +/// +/// Renders in three widths: full labels on desktop, icons only on tablet +/// landscape, and off-canvas below that. The same widget serves all three so +/// the active state and badges never drift apart. +class AppSidebar extends ConsumerWidget { + const AppSidebar({ + super.key, + required this.mode, + this.onDestinationTap, + }); + + final SidebarMode mode; + + /// Lets the drawer close itself after a tap. + final VoidCallback? onDestinationTap; + + @override + Widget build(BuildContext context, WidgetRef ref) { + // The drawer presentation uses the expanded layout at full width. + final expanded = mode != SidebarMode.rail; + final width = mode == SidebarMode.rail + ? PosLayout.railWidth + : PosLayout.expandedWidth; + + return AnimatedContainer( + duration: AppMotion.normal, + curve: AppMotion.emphasized, + width: width, + decoration: const BoxDecoration( + color: AppColors.surface, + border: Border(right: BorderSide(color: AppColors.border)), + ), + child: SafeArea( + right: false, + child: Column( + children: [ + _Brand(expanded: expanded), + const Divider(height: 1), + _Profile(expanded: expanded), + const Divider(height: 1), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.md), + child: Column( + children: [ + for (final section in NavSection.values) + _Section( + section: section, + expanded: expanded, + onDestinationTap: onDestinationTap, + ), + ], + ), + ), + ), + const Divider(height: 1), + _LogoutTile(expanded: expanded), + ], + ), + ), + ); + } +} + +class _Brand extends StatelessWidget { + const _Brand({required this.expanded}); + + final bool expanded; + + @override + Widget build(BuildContext context) { + return Container( + height: AppSizes.headerHeight, + padding: EdgeInsets.symmetric( + horizontal: expanded ? AppSpacing.xl : AppSpacing.md, + ), + alignment: expanded ? Alignment.centerLeft : Alignment.center, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + gradient: AppColors.primaryGradient, + borderRadius: BorderRadius.circular(10), + ), + alignment: Alignment.center, + child: const Text( + 'N', + style: TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.w800, + ), + ), + ), + if (expanded) ...[ + const SizedBox(width: AppSpacing.md), + Flexible( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Nearle', + style: TextStyle( + fontSize: 17, + fontWeight: FontWeight.w700, + letterSpacing: -0.3, + color: AppColors.textPrimary, + height: 1.1, + ), + ), + Text( + 'POS', + style: AppTypography.sectionLabel() + .copyWith(color: AppColors.primary), + ), + ], + ), + ), + ], + ], + ), + ); + } +} + +class _Profile extends ConsumerWidget { + const _Profile({required this.expanded}); + + final bool expanded; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final user = ref.watch(currentUserProvider); + final name = user?.name ?? ref.watch(cashierSessionProvider).name; + final role = user?.role.label ?? ref.watch(cashierSessionProvider).role; + + return Padding( + padding: EdgeInsets.symmetric( + horizontal: expanded ? AppSpacing.lg : AppSpacing.sm, + vertical: AppSpacing.md, + ), + child: Row( + mainAxisAlignment: + expanded ? MainAxisAlignment.start : MainAxisAlignment.center, + children: [ + Container( + width: 38, + height: 38, + decoration: BoxDecoration( + color: AppColors.primarySurface, + borderRadius: AppRadius.brSm, + border: Border.all(color: AppColors.primaryBorder), + ), + alignment: Alignment.center, + child: Text( + Formatters.initials(name), + style: const TextStyle( + color: AppColors.primary, + fontSize: 13, + fontWeight: FontWeight.w700, + ), + ), + ), + if (expanded) ...[ + const SizedBox(width: AppSpacing.md), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + name, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: AppColors.textPrimary, + height: 1.2, + ), + ), + Text( + role, + style: const TextStyle( + fontSize: 11.5, + color: AppColors.textTertiary, + height: 1.3, + ), + ), + ], + ), + ), + ], + ], + ), + ); + } +} + +class _Section extends ConsumerWidget { + const _Section({ + required this.section, + required this.expanded, + this.onDestinationTap, + }); + + final NavSection section; + final bool expanded; + final VoidCallback? onDestinationTap; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final active = ref.watch(activeModuleProvider); + final cartCount = ref.watch(cartItemCountProvider); + final ready = ref.watch(catalogueReadyProvider); + final outstanding = ref + .watch(syncEventsProvider) + .where((e) => e.status != SyncStatus.synced) + .length; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (expanded) + Padding( + padding: const EdgeInsets.fromLTRB( + AppSpacing.xl, + AppSpacing.lg, + AppSpacing.xl, + AppSpacing.sm, + ), + child: Text(section.label.toUpperCase(), + style: AppTypography.sectionLabel()), + ) + else + const Padding( + padding: EdgeInsets.symmetric( + horizontal: AppSpacing.xl, + vertical: AppSpacing.md, + ), + child: Divider(height: 1), + ), + for (final module in section.modules) + _NavTile( + module: module, + expanded: expanded, + selected: active == module, + badge: switch (module) { + PosModule.pos => cartCount > 0 ? cartCount : null, + PosModule.productImport => ready ? null : 1, + PosModule.events => outstanding > 0 ? outstanding : null, + _ => null, + }, + badgeColor: switch (module) { + PosModule.productImport => AppColors.danger, + PosModule.events => AppColors.warning, + _ => AppColors.primary, + }, + onTap: () { + ref.read(activeModuleProvider.notifier).state = module; + onDestinationTap?.call(); + }, + ), + ], + ); + } +} + +class _NavTile extends StatefulWidget { + const _NavTile({ + required this.module, + required this.expanded, + required this.selected, + required this.onTap, + this.badge, + this.badgeColor, + }); + + final PosModule module; + final bool expanded; + final bool selected; + final VoidCallback onTap; + final int? badge; + final Color? badgeColor; + + @override + State<_NavTile> createState() => _NavTileState(); +} + +class _NavTileState extends State<_NavTile> { + bool _hovered = false; + + @override + Widget build(BuildContext context) { + final selected = widget.selected; + final fg = selected + ? AppColors.primary + : (_hovered ? AppColors.textPrimary : AppColors.textSecondary); + + final tile = AnimatedContainer( + duration: AppMotion.fast, + height: AppSizes.navItemHeight, + padding: EdgeInsets.symmetric( + horizontal: widget.expanded ? AppSpacing.md : 0, + ), + decoration: BoxDecoration( + color: selected + ? AppColors.primarySurface + : (_hovered ? AppColors.surfaceAlt : Colors.transparent), + borderRadius: AppRadius.brSm, + ), + child: Row( + mainAxisAlignment: widget.expanded + ? MainAxisAlignment.start + : MainAxisAlignment.center, + children: [ + Stack( + clipBehavior: Clip.none, + children: [ + Icon(widget.module.icon, size: 20, color: fg), + // In rail mode the label is gone, so the badge rides the icon. + if (widget.badge != null && !widget.expanded) + Positioned( + top: -5, + right: -8, + child: _Badge( + value: widget.badge!, + color: widget.badgeColor ?? AppColors.primary, + ), + ), + ], + ), + if (widget.expanded) ...[ + const SizedBox(width: AppSpacing.md), + Expanded( + child: Text( + widget.module.label, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 14, + fontWeight: selected ? FontWeight.w600 : FontWeight.w500, + color: fg, + ), + ), + ), + if (widget.badge != null) + _Badge( + value: widget.badge!, + color: widget.badgeColor ?? AppColors.primary, + ), + ], + ], + ), + ); + + return MouseRegion( + onEnter: (_) => setState(() => _hovered = true), + onExit: (_) => setState(() => _hovered = false), + child: Padding( + padding: EdgeInsets.symmetric( + horizontal: widget.expanded ? AppSpacing.md : AppSpacing.lg, + vertical: 2, + ), + child: Stack( + children: [ + Material( + color: Colors.transparent, + child: InkWell( + onTap: widget.onTap, + borderRadius: AppRadius.brSm, + child: widget.expanded + ? tile + : Tooltip(message: widget.module.title, child: tile), + ), + ), + // Accent bar marking the active destination. + if (selected) + Positioned( + left: 0, + top: 10, + bottom: 10, + child: Container( + width: 3, + decoration: const BoxDecoration( + color: AppColors.primary, + borderRadius: AppRadius.brPill, + ), + ), + ), + ], + ), + ), + ); + } +} + +class _Badge extends StatelessWidget { + const _Badge({required this.value, required this.color}); + + final int value; + final Color color; + + @override + Widget build(BuildContext context) { + return Container( + constraints: const BoxConstraints(minWidth: 19), + height: 19, + padding: const EdgeInsets.symmetric(horizontal: 5), + decoration: BoxDecoration(color: color, borderRadius: AppRadius.brPill), + alignment: Alignment.center, + child: Text( + value > 99 ? '99+' : '$value', + style: const TextStyle( + color: Colors.white, + fontSize: 10.5, + fontWeight: FontWeight.w700, + ), + ), + ); + } +} + +class _LogoutTile extends ConsumerWidget { + const _LogoutTile({required this.expanded}); + + final bool expanded; + + @override + Widget build(BuildContext context, WidgetRef ref) { + return Padding( + padding: const EdgeInsets.all(AppSpacing.md), + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: () => showSignOutDialog(context, ref), + borderRadius: AppRadius.brSm, + child: Container( + height: AppSizes.navItemHeight, + padding: EdgeInsets.symmetric( + horizontal: expanded ? AppSpacing.md : 0, + ), + alignment: expanded ? Alignment.centerLeft : Alignment.center, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.logout_rounded, + size: 19, color: AppColors.danger), + if (expanded) ...[ + const SizedBox(width: AppSpacing.md), + const Text( + 'Logout', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w500, + color: AppColors.danger, + ), + ), + ], + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/presentation/pos/widgets/billing_panel.dart b/lib/presentation/pos/widgets/billing_panel.dart new file mode 100644 index 0000000..c7eb86f --- /dev/null +++ b/lib/presentation/pos/widgets/billing_panel.dart @@ -0,0 +1,368 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/constants/app_constants.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/extensions.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/widgets/empty_state.dart'; +import '../../../core/widgets/primary_button.dart'; +import '../../../domain/entities/cart.dart'; +import '../providers/cart_controller.dart'; +import 'cart_line_tile.dart'; +import 'discount_sheet.dart'; + +/// Always-visible bill on the right of the dashboard. +class BillingPanel extends ConsumerWidget { + const BillingPanel({super.key, this.inSheet = false}); + + final bool inSheet; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final cart = ref.watch(cartControllerProvider); + final controller = ref.read(cartControllerProvider.notifier); + + return Container( + color: AppColors.surface, + child: Column(children: [ + _Header(cart: cart, inSheet: inSheet), + const Divider(height: 1), + Expanded( + child: cart.isEmpty + ? const EmptyState( + title: 'Cart is empty', + message: 'Scan a barcode or tap a product to begin.', + emoji: '🛒', + compact: true, + ) + : ListView.separated( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.lg, + vertical: AppSpacing.md, + ), + itemCount: cart.lines.length, + separatorBuilder: (_, __) => + const SizedBox(height: AppSpacing.sm), + itemBuilder: (_, i) { + // Newest line first mirrors what the cashier just scanned. + final line = cart.lines[cart.lines.length - 1 - i]; + return CartLineTile( + key: ValueKey(line.product.id), + line: line, + onIncrement: () => controller.increment(line.product.id), + onDecrement: () => controller.decrement(line.product.id), + onRemove: () => controller.removeLine(line.product.id), + onDiscount: () => + showLineDiscountSheet(context, ref, line), + ); + }, + ), + ), + if (cart.isNotEmpty) _Summary(cart: cart), + _Actions(cart: cart), + ]), + ); + } +} + +class _Header extends ConsumerWidget { + const _Header({required this.cart, required this.inSheet}); + + final Cart cart; + final bool inSheet; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final controller = ref.read(cartControllerProvider.notifier); + + return Padding( + padding: const EdgeInsets.fromLTRB( + AppSpacing.xl, + AppSpacing.lg, + AppSpacing.md, + AppSpacing.lg, + ), + child: Row(children: [ + Text('Cart', style: context.text.headlineSmall), + const SizedBox(width: AppSpacing.sm), + if (cart.isNotEmpty) + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: AppColors.primarySurface, + borderRadius: AppRadius.brPill, + ), + child: Text( + '${cart.lineCount}', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w800, + fontSize: 13, + ), + ), + ), + const Spacer(), + if (controller.canUndo) + IconButton( + tooltip: 'Undo (F8)', + onPressed: controller.undo, + icon: const Icon(Icons.undo_rounded, size: 19), + color: AppColors.textSecondary, + ), + if (cart.isNotEmpty) ...[ + TextButton.icon( + onPressed: () async { + await controller.park(); + ref.invalidate(parkedBillsProvider); + if (context.mounted) context.showSnack('Bill parked'); + }, + icon: const Icon(Icons.pause_circle_outline_rounded, size: 17), + label: const Text('Park'), + style: TextButton.styleFrom(foregroundColor: AppColors.warning), + ), + TextButton( + onPressed: controller.clear, + style: TextButton.styleFrom(foregroundColor: AppColors.danger), + child: const Text('Clear'), + ), + ], + if (inSheet) + IconButton( + onPressed: () => Navigator.of(context).pop(), + icon: const Icon(Icons.close_rounded), + ), + ]), + ); + } +} + +class _Summary extends ConsumerWidget { + const _Summary({required this.cart}); + + final Cart cart; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final controller = ref.read(cartControllerProvider.notifier); + + return Container( + padding: const EdgeInsets.fromLTRB( + AppSpacing.xl, + AppSpacing.lg, + AppSpacing.xl, + AppSpacing.md, + ), + decoration: const BoxDecoration( + border: Border(top: BorderSide(color: AppColors.divider)), + ), + child: Column(children: [ + if (cart.pointsEarned > 0) + Container( + width: double.infinity, + margin: const EdgeInsets.only(bottom: AppSpacing.md), + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.md, + vertical: AppSpacing.sm + 2, + ), + decoration: BoxDecoration( + color: AppColors.successSurface, + borderRadius: AppRadius.brSm, + ), + child: Row(children: [ + const Icon(Icons.stars_rounded, + size: 16, color: AppColors.success), + const SizedBox(width: AppSpacing.sm), + Text( + 'This sale earns +${cart.pointsEarned} pts', + style: const TextStyle( + color: AppColors.success, + fontWeight: FontWeight.w700, + fontSize: 13, + ), + ), + ]), + ), + + _Row(label: 'Subtotal', value: Formatters.money(cart.subtotal)), + + if (cart.membershipDiscountAmount > 0) + _Row( + label: '${cart.customer!.tier.label} discount', + value: '-${Formatters.money(cart.membershipDiscountAmount)}', + valueColor: AppColors.success, + ), + + _Row( + label: 'GST', + value: Formatters.money(cart.taxAmount), + hint: cart.taxBreakdown.keys.isEmpty + ? null + : cart.taxBreakdown.keys + .map((r) => '${(r * 100).toStringAsFixed(0)}%') + .join(', '), + ), + + InkWell( + onTap: () => showBillDiscountSheet(context, ref), + borderRadius: AppRadius.brXs, + child: _Row( + label: 'Discount', + value: cart.manualBillDiscountAmount > 0 + ? '-${Formatters.money(cart.manualBillDiscountAmount)}' + : '-${Formatters.money(0)}', + valueColor: cart.manualBillDiscountAmount > 0 + ? AppColors.success + : null, + trailingIcon: Icons.edit_outlined, + ), + ), + + if (cart.maxRedeemablePoints > 0 || cart.pointsRedeemed > 0) + InkWell( + onTap: () => cart.pointsRedeemed > 0 + ? controller.clearRedemption() + : controller.redeemAllPoints(), + borderRadius: AppRadius.brXs, + child: _Row( + label: cart.pointsRedeemed > 0 + ? 'Points redeemed (${cart.pointsRedeemed})' + : 'Redeem ${cart.maxRedeemablePoints} points', + value: cart.pointsRedeemed > 0 + ? '-${Formatters.money(cart.loyaltyRedemptionValue)}' + : 'Apply', + valueColor: AppColors.primary, + trailingIcon: cart.pointsRedeemed > 0 + ? Icons.close_rounded + : Icons.add_rounded, + ), + ), + + if (cart.roundOff != 0) + _Row( + label: 'Round Off', + value: '${cart.roundOff >= 0 ? '+' : ''}' + '${Formatters.money(cart.roundOff)}', + ), + + const Padding( + padding: EdgeInsets.symmetric(vertical: AppSpacing.md), + child: Divider(height: 1), + ), + + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('Total', style: context.text.titleLarge), + Text( + Formatters.money(cart.grandTotal), + style: AppTypography.money(26, color: AppColors.primary), + ), + ], + ), + + if (cart.totalSavings > 0) + Padding( + padding: const EdgeInsets.only(top: AppSpacing.xs), + child: Align( + alignment: Alignment.centerRight, + child: Text( + 'You saved ${Formatters.money(cart.totalSavings)}', + style: const TextStyle( + color: AppColors.success, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ]), + ); + } +} + +class _Row extends StatelessWidget { + const _Row({ + required this.label, + required this.value, + this.valueColor, + this.hint, + this.trailingIcon, + }); + + final String label; + final String value; + final Color? valueColor; + final String? hint; + final IconData? trailingIcon; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs + 2), + child: Row(children: [ + Text(label, + style: const TextStyle( + fontSize: 14, + color: AppColors.textSecondary, + )), + if (hint != null) ...[ + const SizedBox(width: AppSpacing.xs), + Text('($hint)', + style: const TextStyle( + fontSize: 11.5, + color: AppColors.textTertiary, + )), + ], + const Spacer(), + Text( + value, + style: AppTypography.money( + 14.5, + weight: FontWeight.w600, + color: valueColor ?? AppColors.textPrimary, + ), + ), + if (trailingIcon != null) ...[ + const SizedBox(width: AppSpacing.xs), + Icon(trailingIcon, size: 14, color: AppColors.textTertiary), + ], + ]), + ); + } +} + +class _Actions extends ConsumerWidget { + const _Actions({required this.cart}); + + final Cart cart; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final enabled = cart.isNotEmpty; + + return Container( + padding: const EdgeInsets.fromLTRB( + AppSpacing.xl, + AppSpacing.sm, + AppSpacing.xl, + AppSpacing.xl, + ), + child: PrimaryButton( + label: 'CHARGE', + large: true, + onPressed: enabled ? () => context.push(AppRoutes.payment) : null, + trailing: enabled + ? Text( + Formatters.money(cart.grandTotal), + style: AppTypography.money(21, color: Colors.white), + ) + : null, + ), + ); + } +} diff --git a/lib/presentation/pos/widgets/cart_fab.dart b/lib/presentation/pos/widgets/cart_fab.dart new file mode 100644 index 0000000..62de33f --- /dev/null +++ b/lib/presentation/pos/widgets/cart_fab.dart @@ -0,0 +1,83 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_animate/flutter_animate.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/formatters.dart'; +import '../providers/cart_controller.dart'; + +/// Floating bill summary shown when the billing panel is collapsed into a +/// sheet. Gives the cashier the running total without opening anything. +class CartFab extends ConsumerWidget { + const CartFab({super.key, required this.onTap}); + + final VoidCallback onTap; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final cart = ref.watch(cartControllerProvider); + if (cart.isEmpty) return const SizedBox.shrink(); + + return Padding( + padding: const EdgeInsets.all(AppSpacing.lg), + child: Material( + color: AppColors.primary, + borderRadius: AppRadius.brLg, + elevation: 0, + child: InkWell( + onTap: onTap, + borderRadius: AppRadius.brLg, + child: Container( + height: AppSizes.buttonHeightLarge, + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xl), + decoration: BoxDecoration( + borderRadius: AppRadius.brLg, + boxShadow: AppColors.shadowLg, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 28, + height: 28, + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.22), + borderRadius: AppRadius.brXs, + ), + alignment: Alignment.center, + child: Text( + '${cart.lineCount}', + style: const TextStyle( + color: Colors.white, + fontSize: 13, + fontWeight: FontWeight.w700, + ), + ), + ), + const SizedBox(width: AppSpacing.md), + const Text( + 'View bill', + style: TextStyle( + color: Colors.white, + fontSize: 15, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(width: AppSpacing.xl), + Text( + Formatters.money(cart.grandTotal), + style: AppTypography.money(19, color: Colors.white), + ), + const SizedBox(width: AppSpacing.sm), + const Icon(Icons.keyboard_arrow_up_rounded, + color: Colors.white, size: 20), + ], + ), + ), + ), + ), + ).animate().fadeIn(duration: 180.ms).slideY(begin: 0.3, end: 0); + } +} diff --git a/lib/presentation/pos/widgets/cart_line_tile.dart b/lib/presentation/pos/widgets/cart_line_tile.dart new file mode 100644 index 0000000..5278c2d --- /dev/null +++ b/lib/presentation/pos/widgets/cart_line_tile.dart @@ -0,0 +1,241 @@ +import 'package:flutter/material.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../domain/entities/cart.dart'; + +/// One row of the bill, with inline quantity stepper. +class CartLineTile extends StatelessWidget { + const CartLineTile({ + super.key, + required this.line, + required this.onIncrement, + required this.onDecrement, + required this.onRemove, + this.onDiscount, + }); + + final CartLine line; + final VoidCallback onIncrement; + final VoidCallback onDecrement; + final VoidCallback onRemove; + final VoidCallback? onDiscount; + + @override + Widget build(BuildContext context) { + final p = line.product; + + return Dismissible( + key: ValueKey('dismiss_${p.id}'), + direction: DismissDirection.endToStart, + onDismissed: (_) => onRemove(), + background: Container( + alignment: Alignment.centerRight, + padding: const EdgeInsets.only(right: AppSpacing.xl), + decoration: BoxDecoration( + color: AppColors.dangerSurface, + borderRadius: AppRadius.brMd, + ), + child: const Icon(Icons.delete_outline_rounded, + color: AppColors.danger), + ), + child: Container( + padding: const EdgeInsets.all(AppSpacing.md), + decoration: BoxDecoration( + color: AppColors.surfaceAlt, + borderRadius: AppRadius.brMd, + border: Border.all( + color: line.exceedsStock ? AppColors.danger : AppColors.border, + ), + ), + child: Column(children: [ + Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Container( + width: 42, + height: 42, + decoration: BoxDecoration( + color: AppColors.surface, + borderRadius: AppRadius.brSm, + border: Border.all(color: AppColors.border), + ), + alignment: Alignment.center, + child: Text(p.emoji, style: const TextStyle(fontSize: 21)), + ), + const SizedBox(width: AppSpacing.md), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + p.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 2), + Row(children: [ + Text( + Formatters.money(p.price), + style: AppTypography.money(13.5, + weight: FontWeight.w600, + color: AppColors.textSecondary), + ), + Text(' / ${p.unit.symbol}', + style: const TextStyle( + fontSize: 11.5, + color: AppColors.textTertiary, + )), + if (line.discount.isActive) ...[ + const SizedBox(width: AppSpacing.sm), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 5, vertical: 1), + decoration: BoxDecoration( + color: AppColors.successSurface, + borderRadius: BorderRadius.circular(4), + ), + child: Text( + line.discount.label, + style: const TextStyle( + fontSize: 10, + color: AppColors.success, + fontWeight: FontWeight.w700, + ), + ), + ), + ], + ]), + ], + ), + ), + IconButton( + onPressed: onRemove, + icon: const Icon(Icons.close_rounded, size: 18), + color: AppColors.textTertiary, + constraints: const BoxConstraints(minWidth: 32, minHeight: 32), + padding: EdgeInsets.zero, + tooltip: 'Remove', + ), + ]), + + const SizedBox(height: AppSpacing.sm), + + Row(children: [ + _Stepper( + quantity: line.quantity, + unit: p.unit.symbol, + onIncrement: onIncrement, + onDecrement: onDecrement, + ), + if (onDiscount != null) ...[ + const SizedBox(width: AppSpacing.sm), + IconButton( + onPressed: onDiscount, + icon: const Icon(Icons.local_offer_outlined, size: 17), + color: AppColors.textSecondary, + constraints: const BoxConstraints(minWidth: 34, minHeight: 34), + padding: EdgeInsets.zero, + tooltip: 'Line discount', + ), + ], + const Spacer(), + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + if (line.discountAmount > 0) + Text( + Formatters.money(line.grossAmount), + style: const TextStyle( + fontSize: 11.5, + color: AppColors.textTertiary, + decoration: TextDecoration.lineThrough, + ), + ), + Text( + Formatters.money(line.payable), + style: AppTypography.money(16), + ), + ], + ), + ]), + + if (line.exceedsStock) + Padding( + padding: const EdgeInsets.only(top: AppSpacing.sm), + child: Row(children: [ + const Icon(Icons.error_outline_rounded, + size: 14, color: AppColors.danger), + const SizedBox(width: AppSpacing.xs), + Text( + 'Only ${p.stock.toStringAsFixed(0)} ${p.unit.symbol} ' + 'available', + style: const TextStyle( + fontSize: 11.5, + color: AppColors.danger, + fontWeight: FontWeight.w600, + ), + ), + ]), + ), + ]), + ), + ); + } +} + +class _Stepper extends StatelessWidget { + const _Stepper({ + required this.quantity, + required this.unit, + required this.onIncrement, + required this.onDecrement, + }); + + final double quantity; + final String unit; + final VoidCallback onIncrement; + final VoidCallback onDecrement; + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration( + color: AppColors.surface, + borderRadius: AppRadius.brSm, + border: Border.all(color: AppColors.border), + ), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + _btn(Icons.remove_rounded, onDecrement), + Container( + constraints: const BoxConstraints(minWidth: 42), + alignment: Alignment.center, + child: Text( + quantity % 1 == 0 + ? quantity.toStringAsFixed(0) + : quantity.toStringAsFixed(2), + style: AppTypography.money(15.5), + ), + ), + _btn(Icons.add_rounded, onIncrement), + ]), + ); + } + + Widget _btn(IconData icon, VoidCallback onTap) => Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + borderRadius: AppRadius.brSm, + child: SizedBox( + width: 34, + height: 34, + child: Icon(icon, size: 17, color: AppColors.primary), + ), + ), + ); +} diff --git a/lib/presentation/pos/widgets/category_chips.dart b/lib/presentation/pos/widgets/category_chips.dart new file mode 100644 index 0000000..bcbf105 --- /dev/null +++ b/lib/presentation/pos/widgets/category_chips.dart @@ -0,0 +1,117 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../domain/entities/product.dart'; +import '../providers/catalog_providers.dart'; + +class CategoryChips extends ConsumerWidget { + const CategoryChips({super.key, this.horizontalPadding = AppSpacing.xxl}); + + /// Matched to the surrounding content gutter by the dashboard layout. + final double horizontalPadding; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final selected = ref.watch(selectedCategoryProvider); + final counts = ref.watch(categoryCountsProvider).value ?? const {}; + + return SizedBox( + height: 52, + child: ListView( + scrollDirection: Axis.horizontal, + padding: EdgeInsets.symmetric(horizontal: horizontalPadding), + children: [ + _Chip( + label: 'All', + selected: selected == null, + onTap: () => + ref.read(selectedCategoryProvider.notifier).state = null, + ), + for (final category in ProductCategory.values) + _Chip( + label: category.label, + emoji: category.emoji, + count: counts[category], + selected: selected == category, + onTap: () => ref.read(selectedCategoryProvider.notifier).state = + selected == category ? null : category, + ), + ], + ), + ); + } +} + +class _Chip extends StatelessWidget { + const _Chip({ + required this.label, + required this.selected, + required this.onTap, + this.emoji, + this.count, + }); + + final String label; + final bool selected; + final VoidCallback onTap; + final String? emoji; + final int? count; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(right: AppSpacing.md), + child: Material( + color: selected ? AppColors.primary : AppColors.surface, + borderRadius: AppRadius.brPill, + child: InkWell( + onTap: onTap, + borderRadius: AppRadius.brPill, + child: AnimatedContainer( + duration: AppMotion.fast, + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.xl, + vertical: AppSpacing.md, + ), + decoration: BoxDecoration( + borderRadius: AppRadius.brPill, + border: Border.all( + color: selected ? AppColors.primary : AppColors.border, + ), + boxShadow: selected ? AppColors.shadowSm : null, + ), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + if (emoji != null) ...[ + Text(emoji!, style: const TextStyle(fontSize: 15)), + const SizedBox(width: AppSpacing.sm), + ], + Text( + label, + style: TextStyle( + color: selected ? Colors.white : AppColors.textPrimary, + fontWeight: FontWeight.w600, + fontSize: 14.5, + ), + ), + if (count != null) ...[ + const SizedBox(width: AppSpacing.sm), + Text( + '$count', + style: TextStyle( + color: selected + ? Colors.white.withValues(alpha: 0.75) + : AppColors.textTertiary, + fontSize: 12, + fontWeight: FontWeight.w700, + ), + ), + ], + ]), + ), + ), + ), + ); + } +} diff --git a/lib/presentation/pos/widgets/customer_bar.dart b/lib/presentation/pos/widgets/customer_bar.dart new file mode 100644 index 0000000..861bd7f --- /dev/null +++ b/lib/presentation/pos/widgets/customer_bar.dart @@ -0,0 +1,99 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/extensions.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/widgets/status_pill.dart'; +import '../providers/cart_controller.dart'; + +/// Strip above the product grid showing who the sale belongs to. +class CustomerBar extends ConsumerWidget { + const CustomerBar({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final customer = ref.watch( + cartControllerProvider.select((cart) => cart.customer), + ); + + return Container( + height: AppSizes.customerBarHeight, + color: AppColors.surface, + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xxl), + child: Row(children: [ + CircleAvatar( + radius: 20, + backgroundColor: customer == null + ? AppColors.border + : AppColors.primarySurface, + child: customer == null + ? const Icon(Icons.directions_walk_rounded, + size: 20, color: AppColors.textSecondary) + : Text( + Formatters.initials(customer.name), + style: const TextStyle( + color: AppColors.primary, + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + ), + const SizedBox(width: AppSpacing.md), + Flexible( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row(mainAxisSize: MainAxisSize.min, children: [ + Flexible( + child: Text( + customer?.name ?? 'Walk-in Customer', + style: context.text.titleMedium, + overflow: TextOverflow.ellipsis, + ), + ), + if (customer != null) ...[ + const SizedBox(width: AppSpacing.sm), + StatusPill.tier(customer.tier, dense: true), + ], + ]), + if (customer != null) + Text( + '${Formatters.mobile(customer.mobile)} · ' + '${customer.loyaltyPoints} pts', + style: context.text.bodySmall, + ) + else + Text('No loyalty tracking for this sale', + style: context.text.bodySmall), + ], + ), + ), + const Spacer(), + if (customer != null) + TextButton.icon( + onPressed: () => + ref.read(cartControllerProvider.notifier).attachCustomer(null), + icon: const Icon(Icons.person_off_outlined, size: 17), + label: const Text('Detach'), + style: TextButton.styleFrom( + foregroundColor: AppColors.textSecondary), + ), + const SizedBox(width: AppSpacing.sm), + OutlinedButton.icon( + onPressed: () => context.push(AppRoutes.existingCustomer), + icon: const Icon(Icons.sync_alt_rounded, size: 17), + label: Text(customer == null ? 'Add Customer' : 'Change'), + style: OutlinedButton.styleFrom( + minimumSize: const Size(0, 44), + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), + ), + ), + ]), + ); + } +} diff --git a/lib/presentation/pos/widgets/discount_sheet.dart b/lib/presentation/pos/widgets/discount_sheet.dart new file mode 100644 index 0000000..29c1914 --- /dev/null +++ b/lib/presentation/pos/widgets/discount_sheet.dart @@ -0,0 +1,213 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/widgets/primary_button.dart'; +import '../../../domain/entities/cart.dart'; +import '../providers/cart_controller.dart'; + +Future showLineDiscountSheet( + BuildContext context, + WidgetRef ref, + CartLine line, +) { + return _show( + context: context, + title: line.product.name, + subtitle: 'Line value ${Formatters.money(line.grossAmount)}', + current: line.discount, + onApply: (d) => ref + .read(cartControllerProvider.notifier) + .applyLineDiscount(line.product.id, d), + ); +} + +Future showBillDiscountSheet(BuildContext context, WidgetRef ref) { + final cart = ref.read(cartControllerProvider); + return _show( + context: context, + title: 'Bill discount', + subtitle: 'Subtotal ${Formatters.money(cart.subtotal)}', + current: cart.billDiscount, + onApply: (d) => + ref.read(cartControllerProvider.notifier).applyBillDiscount(d), + ); +} + +Future _show({ + required BuildContext context, + required String title, + required String subtitle, + required Discount current, + required ValueChanged onApply, +}) { + return showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (_) => _DiscountSheet( + title: title, + subtitle: subtitle, + current: current, + onApply: onApply, + ), + ); +} + +class _DiscountSheet extends StatefulWidget { + const _DiscountSheet({ + required this.title, + required this.subtitle, + required this.current, + required this.onApply, + }); + + final String title; + final String subtitle; + final Discount current; + final ValueChanged onApply; + + @override + State<_DiscountSheet> createState() => _DiscountSheetState(); +} + +class _DiscountSheetState extends State<_DiscountSheet> { + late DiscountType _type = + widget.current.type == DiscountType.none + ? DiscountType.percentage + : widget.current.type; + late final TextEditingController _value = TextEditingController( + text: widget.current.isActive + ? widget.current.value.toStringAsFixed(0) + : '', + ); + + @override + void dispose() { + _value.dispose(); + super.dispose(); + } + + void _apply() { + final v = double.tryParse(_value.text.trim()) ?? 0; + widget.onApply( + v <= 0 ? Discount.none : Discount(type: _type, value: v), + ); + Navigator.of(context).pop(); + } + + @override + Widget build(BuildContext context) { + return Padding( + padding: EdgeInsets.only( + bottom: MediaQuery.viewInsetsOf(context).bottom, + ), + child: Container( + padding: const EdgeInsets.all(AppSpacing.xxl), + decoration: const BoxDecoration( + color: AppColors.surface, + borderRadius: + BorderRadius.vertical(top: Radius.circular(AppRadius.xxl)), + ), + child: Column(mainAxisSize: MainAxisSize.min, children: [ + Container( + width: 40, + height: 4, + decoration: BoxDecoration( + color: AppColors.border, + borderRadius: AppRadius.brPill, + ), + ), + const SizedBox(height: AppSpacing.xl), + + Text(widget.title, + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w700)), + const SizedBox(height: 2), + Text(widget.subtitle, + style: const TextStyle( + fontSize: 13, + color: AppColors.textSecondary, + )), + const SizedBox(height: AppSpacing.xxl), + + SegmentedButton( + segments: const [ + ButtonSegment( + value: DiscountType.percentage, + label: Text('Percentage'), + icon: Icon(Icons.percent_rounded, size: 17), + ), + ButtonSegment( + value: DiscountType.flat, + label: Text('Flat amount'), + icon: Icon(Icons.currency_rupee_rounded, size: 17), + ), + ], + selected: {_type}, + onSelectionChanged: (s) => setState(() => _type = s.first), + ), + const SizedBox(height: AppSpacing.xl), + + TextField( + controller: _value, + autofocus: true, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + inputFormatters: [ + FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}')), + ], + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.w700), + textAlign: TextAlign.center, + decoration: InputDecoration( + hintText: '0', + prefixText: _type == DiscountType.flat ? '₹ ' : null, + suffixText: _type == DiscountType.percentage ? '%' : null, + ), + onSubmitted: (_) => _apply(), + ), + const SizedBox(height: AppSpacing.lg), + + Wrap( + spacing: AppSpacing.sm, + children: (_type == DiscountType.percentage + ? const [5, 10, 15, 20, 25] + : const [10, 20, 50, 100, 200]) + .map((v) => ActionChip( + label: Text(_type == DiscountType.percentage + ? '$v%' + : '₹$v'), + onPressed: () => + setState(() => _value.text = v.toString()), + )) + .toList(), + ), + const SizedBox(height: AppSpacing.xxl), + + Row(children: [ + Expanded( + child: PrimaryButton( + label: 'Remove', + tone: ButtonTone.neutral, + onPressed: () { + widget.onApply(Discount.none); + Navigator.of(context).pop(); + }, + ), + ), + const SizedBox(width: AppSpacing.md), + Expanded( + flex: 2, + child: PrimaryButton( + label: 'Apply discount', + icon: Icons.check_rounded, + onPressed: _apply, + ), + ), + ]), + ]), + ), + ); + } +} diff --git a/lib/presentation/pos/widgets/page_header.dart b/lib/presentation/pos/widgets/page_header.dart new file mode 100644 index 0000000..56f5f32 --- /dev/null +++ b/lib/presentation/pos/widgets/page_header.dart @@ -0,0 +1,324 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../app/providers.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_layout.dart'; +import '../../../core/utils/formatters.dart'; +import '../providers/cart_controller.dart'; +import '../providers/navigation_provider.dart'; + +/// White page header: breadcrumb, title, and the terminal's quick actions. +/// +/// Replaces the old purple app bar now that branding lives in the sidebar. +class PageHeader extends ConsumerWidget { + const PageHeader({ + super.key, + required this.layout, + this.onMenuTap, + }); + + final PosLayout layout; + final VoidCallback? onMenuTap; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final module = ref.watch(activeModuleProvider); + final now = ref.watch(clockProvider).value ?? DateTime.now(); + final compact = layout.sidebarIsDrawer; + + return Container( + constraints: const BoxConstraints(minHeight: AppSizes.headerHeight), + padding: EdgeInsets.symmetric( + horizontal: layout.contentPadding, + vertical: AppSpacing.md, + ), + decoration: const BoxDecoration( + color: AppColors.surface, + border: Border(bottom: BorderSide(color: AppColors.border)), + ), + child: Row( + children: [ + if (compact) ...[ + IconButton( + onPressed: onMenuTap, + icon: const Icon(Icons.menu_rounded), + tooltip: 'Menu', + color: AppColors.textPrimary, + ), + const SizedBox(width: AppSpacing.xs), + ], + + Flexible( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + module.title, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 19, + fontWeight: FontWeight.w600, + letterSpacing: -0.4, + color: AppColors.textPrimary, + height: 1.2, + ), + ), + if (!compact) _Breadcrumb(module: module), + ], + ), + ), + + const Spacer(), + + if (!compact) ...[ + const _LivePill(), + const SizedBox(width: AppSpacing.lg), + Text( + Formatters.time(now), + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w500, + color: AppColors.textSecondary, + fontFeatures: [FontFeature.tabularFigures()], + ), + ), + const SizedBox(width: AppSpacing.lg), + Container(width: 1, height: 26, color: AppColors.border), + const SizedBox(width: AppSpacing.lg), + ], + + _ParkedBillsButton(compact: compact), + const SizedBox(width: AppSpacing.sm), + _NewSaleButton(compact: compact), + ], + ), + ); + } +} + +class _Breadcrumb extends StatelessWidget { + const _Breadcrumb({required this.module}); + + final PosModule module; + + @override + Widget build(BuildContext context) { + const style = TextStyle(fontSize: 12, color: AppColors.textTertiary); + + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Home', style: style), + const Padding( + padding: EdgeInsets.symmetric(horizontal: AppSpacing.xs + 2), + child: Icon(Icons.chevron_right_rounded, + size: 13, color: AppColors.textTertiary), + ), + Text(module.section.label, style: style), + const Padding( + padding: EdgeInsets.symmetric(horizontal: AppSpacing.xs + 2), + child: Icon(Icons.chevron_right_rounded, + size: 13, color: AppColors.textTertiary), + ), + Text( + module.label, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: AppColors.primary, + ), + ), + ], + ); + } +} + +class _LivePill extends StatefulWidget { + const _LivePill(); + + @override + State<_LivePill> createState() => _LivePillState(); +} + +class _LivePillState extends State<_LivePill> + with SingleTickerProviderStateMixin { + late final AnimationController _c = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 1400), + )..repeat(reverse: true); + + @override + void dispose() { + _c.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.md, + vertical: AppSpacing.xs + 2, + ), + decoration: BoxDecoration( + color: AppColors.successSurface, + borderRadius: AppRadius.brPill, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + FadeTransition( + opacity: _c, + child: Container( + width: 7, + height: 7, + decoration: const BoxDecoration( + color: AppColors.success, + shape: BoxShape.circle, + ), + ), + ), + const SizedBox(width: AppSpacing.xs + 2), + const Text( + 'LIVE', + style: TextStyle( + color: AppColors.success, + fontSize: 10.5, + fontWeight: FontWeight.w700, + letterSpacing: 0.8, + ), + ), + ], + ), + ); + } +} + +class _ParkedBillsButton extends ConsumerWidget { + const _ParkedBillsButton({required this.compact}); + + final bool compact; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final parked = ref.watch(parkedBillsProvider).value ?? const []; + + if (compact) { + return IconButton( + tooltip: 'Parked bills', + onPressed: () => _openParked(context, ref), + icon: Badge( + isLabelVisible: parked.isNotEmpty, + label: Text('${parked.length}'), + backgroundColor: AppColors.warning, + child: const Icon(Icons.pause_circle_outline_rounded), + ), + ); + } + + return OutlinedButton.icon( + onPressed: () => _openParked(context, ref), + icon: const Icon(Icons.pause_circle_outline_rounded, size: 17), + label: Text( + parked.isEmpty ? 'Parked' : 'Parked (${parked.length})', + ), + style: OutlinedButton.styleFrom( + minimumSize: const Size(0, 42), + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), + foregroundColor: AppColors.textSecondary, + ), + ); + } + + void _openParked(BuildContext context, WidgetRef ref) { + final parked = ref.read(parkedBillsProvider).value ?? const []; + + if (parked.isEmpty) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(const SnackBar(content: Text('No parked bills.'))); + return; + } + + showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text('Parked bills'), + content: SizedBox( + width: 380, + child: ListView.separated( + shrinkWrap: true, + itemCount: parked.length, + separatorBuilder: (_, __) => const Divider(height: 1), + itemBuilder: (_, i) { + final bill = parked[i]; + return ListTile( + leading: const Icon(Icons.receipt_long_rounded, + color: AppColors.primary), + title: Text(bill.displayLabel), + subtitle: Text( + '${bill.cart.lineCount} items · ' + '${Formatters.money(bill.cart.grandTotal)} · ' + '${Formatters.time(bill.parkedAt)}', + ), + onTap: () async { + await ref + .read(cartControllerProvider.notifier) + .resume(bill); + ref.invalidate(parkedBillsProvider); + if (context.mounted) Navigator.of(context).pop(); + }, + ); + }, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Close'), + ), + ], + ), + ); + } +} + +class _NewSaleButton extends ConsumerWidget { + const _NewSaleButton({required this.compact}); + + final bool compact; + + @override + Widget build(BuildContext context, WidgetRef ref) { + void start() { + ref.read(cartControllerProvider.notifier).reset(); + context.go(AppRoutes.welcome); + } + + if (compact) { + return IconButton.filled( + tooltip: 'New sale', + onPressed: start, + icon: const Icon(Icons.add_rounded), + style: IconButton.styleFrom(backgroundColor: AppColors.primary), + ); + } + + return FilledButton.icon( + onPressed: start, + icon: const Icon(Icons.add_rounded, size: 18), + label: const Text('New Sale'), + style: FilledButton.styleFrom( + backgroundColor: AppColors.primary, + minimumSize: const Size(0, 42), + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), + shape: const RoundedRectangleBorder(borderRadius: AppRadius.brSm), + ), + ); + } +} diff --git a/lib/presentation/pos/widgets/product_card.dart b/lib/presentation/pos/widgets/product_card.dart new file mode 100644 index 0000000..3458866 --- /dev/null +++ b/lib/presentation/pos/widgets/product_card.dart @@ -0,0 +1,217 @@ +import 'package:flutter/material.dart'; + +import '../../../core/constants/app_constants.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../domain/entities/product.dart'; + +/// Tapping anywhere on the card bills the item — no confirm step. +class ProductCard extends StatefulWidget { + const ProductCard({ + super.key, + required this.product, + required this.onTap, + this.inCartQuantity = 0, + }); + + final Product product; + final VoidCallback onTap; + final double inCartQuantity; + + @override + State createState() => _ProductCardState(); +} + +class _ProductCardState extends State { + bool _hovered = false; + bool _pressed = false; + + @override + Widget build(BuildContext context) { + final p = widget.product; + final disabled = p.isOutOfStock; + final inCart = widget.inCartQuantity > 0; + + return MouseRegion( + cursor: disabled ? SystemMouseCursors.forbidden : SystemMouseCursors.click, + onEnter: (_) => setState(() => _hovered = true), + onExit: (_) => setState(() => _hovered = false), + child: GestureDetector( + onTapDown: (_) => setState(() => _pressed = true), + onTapUp: (_) => setState(() => _pressed = false), + onTapCancel: () => setState(() => _pressed = false), + onTap: disabled ? null : widget.onTap, + child: AnimatedScale( + scale: _pressed ? 0.96 : 1, + duration: AppMotion.instant, + child: AnimatedContainer( + duration: AppMotion.fast, + decoration: BoxDecoration( + color: disabled ? AppColors.surfaceAlt : AppColors.surface, + borderRadius: AppRadius.brLg, + border: Border.all( + color: inCart + ? AppColors.primary + : (_hovered ? AppColors.primaryBorder : AppColors.border), + width: inCart ? 1.8 : 1, + ), + boxShadow: _hovered && !disabled + ? AppColors.shadowMd + : AppColors.shadowSm, + ), + child: Stack(children: [ + Padding( + padding: const EdgeInsets.all(AppSpacing.md), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Opacity( + opacity: disabled ? 0.4 : 1, + child: Text(p.emoji, + style: const TextStyle(fontSize: 40)), + ), + const SizedBox(height: AppSpacing.sm), + Text( + p.name, + maxLines: 2, + textAlign: TextAlign.center, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + height: 1.25, + color: disabled + ? AppColors.textTertiary + : AppColors.textPrimary, + ), + ), + const SizedBox(height: AppSpacing.xs + 2), + Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + Formatters.money(p.price), + style: AppTypography.money(17, + color: disabled + ? AppColors.textTertiary + : AppColors.primary), + ), + if (p.hasDiscount) ...[ + const SizedBox(width: AppSpacing.xs + 2), + Padding( + padding: const EdgeInsets.only(bottom: 1.5), + child: Text( + Formatters.money(p.mrp!), + style: const TextStyle( + fontSize: 11.5, + color: AppColors.textTertiary, + decoration: TextDecoration.lineThrough, + ), + ), + ), + ], + ], + ), + const SizedBox(height: AppSpacing.xs), + Text( + disabled + ? 'Out of stock' + : '${p.stock.toStringAsFixed(0)} in stock', + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w500, + color: disabled + ? AppColors.danger + : (p.isLowStock + ? AppColors.warning + : AppColors.textTertiary), + ), + ), + ], + ), + ), + + if (p.hasDiscount && !disabled) + Positioned( + top: AppSpacing.sm, + left: AppSpacing.sm, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: AppColors.success, + borderRadius: BorderRadius.circular(5), + ), + child: Text( + '${p.discountPercent.toStringAsFixed(0)}%', + style: const TextStyle( + color: Colors.white, + fontSize: 10, + fontWeight: FontWeight.w800, + ), + ), + ), + ), + + if (p.isLowStock && !disabled) + const Positioned( + top: AppSpacing.sm, + right: AppSpacing.sm, + child: Icon(Icons.warning_amber_rounded, + size: 15, color: AppColors.warning), + ), + + // Quantity badge once the item is on the bill. + if (inCart) + Positioned( + top: AppSpacing.sm, + right: AppSpacing.sm, + child: Container( + constraints: const BoxConstraints(minWidth: 24), + height: 24, + padding: const EdgeInsets.symmetric(horizontal: 6), + decoration: const BoxDecoration( + color: AppColors.primary, + shape: BoxShape.rectangle, + borderRadius: AppRadius.brPill, + ), + alignment: Alignment.center, + child: Text( + widget.inCartQuantity % 1 == 0 + ? widget.inCartQuantity.toStringAsFixed(0) + : widget.inCartQuantity.toStringAsFixed(2), + style: const TextStyle( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.w800, + ), + ), + ), + ), + + // Hover-only add affordance keeps the resting card clean. + if (_hovered && !disabled && !inCart) + Positioned( + bottom: AppSpacing.sm, + right: AppSpacing.sm, + child: Container( + width: 28, + height: 28, + decoration: const BoxDecoration( + color: AppColors.primary, + shape: BoxShape.circle, + ), + child: const Icon(Icons.add_rounded, + size: 18, color: Colors.white), + ), + ), + ]), + ), + ), + ), + ); + } +} diff --git a/lib/presentation/pos/widgets/product_grid.dart b/lib/presentation/pos/widgets/product_grid.dart new file mode 100644 index 0000000..2bf3731 --- /dev/null +++ b/lib/presentation/pos/widgets/product_grid.dart @@ -0,0 +1,82 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/widgets/empty_state.dart'; +import '../providers/cart_controller.dart'; +import '../providers/catalog_providers.dart'; +import 'product_card.dart'; + +/// Responsive grid that fills the available width with cards of a stable +/// minimum size, rather than a fixed column count. +class ProductGrid extends ConsumerWidget { + const ProductGrid({ + super.key, + this.horizontalPadding = AppSpacing.xxl, + this.tileExtent = 186, + this.bottomPadding = AppSpacing.xxl, + }); + + /// Content gutter, supplied by the dashboard layout. + final double horizontalPadding; + + /// Maximum card width; the grid fits as many columns as will fit. + final double tileExtent; + + /// Extra space so the floating bill button never covers the last row. + final double bottomPadding; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final products = ref.watch(visibleProductsProvider); + final cart = ref.watch(cartControllerProvider); + + return products.when( + loading: () => const Center( + child: CircularProgressIndicator(color: AppColors.primary), + ), + error: (e, _) => EmptyState( + title: 'Could not load products', + message: '$e', + emoji: '⚠️', + ), + data: (items) { + if (items.isEmpty) { + return const EmptyState( + title: 'No products match', + message: 'Try a different search term or category.', + emoji: '🔎', + ); + } + + return GridView.builder( + padding: EdgeInsets.fromLTRB( + horizontalPadding, + 0, + horizontalPadding, + bottomPadding, + ), + gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: tileExtent, + mainAxisSpacing: AppSpacing.md, + crossAxisSpacing: AppSpacing.md, + childAspectRatio: AppSizes.productCardAspect, + ), + itemCount: items.length, + itemBuilder: (context, i) { + final product = items[i]; + return ProductCard( + key: ValueKey(product.id), + product: product, + inCartQuantity: cart.lineFor(product.id)?.quantity ?? 0, + onTap: () => ref + .read(cartControllerProvider.notifier) + .addProduct(product), + ); + }, + ); + }, + ); + } +} diff --git a/lib/presentation/pos/widgets/scan_toast.dart b/lib/presentation/pos/widgets/scan_toast.dart new file mode 100644 index 0000000..eac682c --- /dev/null +++ b/lib/presentation/pos/widgets/scan_toast.dart @@ -0,0 +1,121 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_animate/flutter_animate.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../providers/cart_controller.dart'; + +/// Brief floating confirmation after a scan. +/// +/// Deliberately not a dialog: the cashier must never have to dismiss anything +/// between items. +class ScanToast extends ConsumerStatefulWidget { + const ScanToast({super.key}); + + @override + ConsumerState createState() => _ScanToastState(); +} + +class _ScanToastState extends ConsumerState { + Timer? _timer; + ScanFeedback? _visible; + + void _show(ScanFeedback feedback) { + _timer?.cancel(); + setState(() => _visible = feedback); + _timer = Timer( + const Duration(milliseconds: 1600), + () { + if (mounted) setState(() => _visible = null); + }, + ); + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + ref.listen(scanFeedbackProvider, (prev, next) { + if (next != null) _show(next); + }); + + final feedback = _visible; + if (feedback == null) return const SizedBox.shrink(); + + final success = feedback.isSuccess; + final color = success ? AppColors.success : AppColors.danger; + final product = feedback.product; + + final message = feedback.message ?? + switch (feedback.outcome) { + ScanOutcome.added => 'Added to bill', + ScanOutcome.incremented => 'Quantity updated', + ScanOutcome.notFound => 'Product not found', + ScanOutcome.outOfStock => 'Out of stock', + }; + + return Container( + margin: const EdgeInsets.symmetric(horizontal: AppSpacing.xxl), + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.xl, + vertical: AppSpacing.md, + ), + decoration: BoxDecoration( + color: AppColors.textPrimary, + borderRadius: AppRadius.brPill, + boxShadow: AppColors.shadowLg, + ), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Container( + width: 26, + height: 26, + decoration: BoxDecoration(color: color, shape: BoxShape.circle), + child: Icon( + success ? Icons.check_rounded : Icons.priority_high_rounded, + size: 17, + color: Colors.white, + ), + ), + const SizedBox(width: AppSpacing.md), + if (product != null) ...[ + Text(product.emoji, style: const TextStyle(fontSize: 17)), + const SizedBox(width: AppSpacing.sm), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 220), + child: Text( + product.name, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.w700, + fontSize: 14.5, + ), + ), + ), + const SizedBox(width: AppSpacing.sm), + Container(width: 1, height: 16, color: Colors.white24), + const SizedBox(width: AppSpacing.sm), + ], + Text( + message, + style: TextStyle( + color: Colors.white.withValues(alpha: 0.85), + fontSize: 13.5, + ), + ), + ]), + ) + .animate(key: ValueKey(feedback.stamp)) + .fadeIn(duration: 140.ms) + .slideY(begin: 0.4, end: 0, curve: Curves.easeOutBack) + .then(delay: 1200.ms) + .fadeOut(duration: 250.ms); + } +} diff --git a/lib/presentation/pos/widgets/search_field.dart b/lib/presentation/pos/widgets/search_field.dart new file mode 100644 index 0000000..23c5576 --- /dev/null +++ b/lib/presentation/pos/widgets/search_field.dart @@ -0,0 +1,103 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/validators.dart'; +import '../providers/cart_controller.dart'; +import '../providers/catalog_providers.dart'; + +/// Doubles as the barcode input. +/// +/// If the submitted text looks like a barcode we bill it immediately and clear +/// the field; otherwise it stays as a live search term. +class PosSearchField extends ConsumerStatefulWidget { + const PosSearchField({super.key, this.focusNode}); + + final FocusNode? focusNode; + + @override + ConsumerState createState() => _PosSearchFieldState(); +} + +class _PosSearchFieldState extends ConsumerState { + final _controller = TextEditingController(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _submit(String value) { + final text = value.trim(); + if (text.isEmpty) return; + + if (Validators.isLikelyBarcode(text)) { + ref.read(cartControllerProvider.notifier).scanBarcode(text); + _controller.clear(); + ref.read(searchQueryProvider.notifier).state = ''; + } + } + + @override + Widget build(BuildContext context) { + final query = ref.watch(searchQueryProvider); + + return TextField( + controller: _controller, + focusNode: widget.focusNode, + autofocus: true, + textInputAction: TextInputAction.search, + style: const TextStyle(fontSize: 16), + onChanged: (v) => ref.read(searchQueryProvider.notifier).state = v, + onSubmitted: _submit, + decoration: InputDecoration( + hintText: 'Search product, scan barcode or enter SKU…', + prefixIcon: const Padding( + padding: EdgeInsets.only(left: AppSpacing.md, right: AppSpacing.sm), + child: Icon(Icons.search_rounded, color: AppColors.textTertiary), + ), + prefixIconConstraints: const BoxConstraints(minWidth: 0), + contentPadding: const EdgeInsets.symmetric( + horizontal: AppSpacing.lg, + vertical: AppSpacing.lg + 2, + ), + suffixIcon: Row(mainAxisSize: MainAxisSize.min, children: [ + if (query.isNotEmpty) + IconButton( + tooltip: 'Clear', + icon: const Icon(Icons.close_rounded, size: 20), + color: AppColors.textTertiary, + onPressed: () { + _controller.clear(); + ref.read(searchQueryProvider.notifier).state = ''; + }, + ), + Container( + margin: const EdgeInsets.only(right: AppSpacing.sm), + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.md, + vertical: AppSpacing.sm, + ), + decoration: BoxDecoration( + color: AppColors.primarySurface, + borderRadius: AppRadius.brSm, + ), + child: const Row(mainAxisSize: MainAxisSize.min, children: [ + Icon(Icons.qr_code_scanner_rounded, + size: 18, color: AppColors.primary), + SizedBox(width: AppSpacing.xs + 2), + Text('Scanner ready', + style: TextStyle( + color: AppColors.primary, + fontSize: 12, + fontWeight: FontWeight.w600, + )), + ]), + ), + ]), + ), + ); + } +} diff --git a/lib/presentation/receipt/screens/receipt_screen.dart b/lib/presentation/receipt/screens/receipt_screen.dart new file mode 100644 index 0000000..718f113 --- /dev/null +++ b/lib/presentation/receipt/screens/receipt_screen.dart @@ -0,0 +1,250 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_animate/flutter_animate.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../app/providers.dart'; +import '../../../core/constants/app_constants.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/extensions.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/widgets/glass_card.dart'; +import '../../../core/widgets/primary_button.dart'; +import '../../../domain/entities/transaction.dart'; +import '../../pos/providers/cart_controller.dart'; +import '../widgets/receipt_preview.dart'; + +/// Confirmation screen. Counts down and starts the next sale on its own so an +/// unattended terminal never sits on a finished bill. +class ReceiptScreen extends ConsumerStatefulWidget { + const ReceiptScreen({super.key, required this.transaction}); + + final SaleTransaction transaction; + + @override + ConsumerState createState() => _ReceiptScreenState(); +} + +class _ReceiptScreenState extends ConsumerState { + late int _seconds = AppConstants.postSaleResetDelay.inSeconds + 5; + Timer? _timer; + + @override + void initState() { + super.initState(); + _timer = Timer.periodic(const Duration(seconds: 1), (t) { + if (!mounted) return; + setState(() => _seconds--); + if (_seconds <= 0) _newSale(); + }); + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + void _cancelAutoReturn() { + _timer?.cancel(); + if (mounted) setState(() => _seconds = -1); + } + + void _newSale() { + _timer?.cancel(); + ref.read(cartControllerProvider.notifier).reset(); + if (mounted) context.go(AppRoutes.welcome); + } + + void _continueBilling() { + _timer?.cancel(); + ref.read(cartControllerProvider.notifier).reset(); + if (mounted) context.go(AppRoutes.pos); + } + + @override + Widget build(BuildContext context) { + final txn = widget.transaction; + + return Scaffold( + backgroundColor: AppColors.background, + body: SafeArea( + child: Listener( + onPointerDown: (_) => _cancelAutoReturn(), + child: Padding( + padding: const EdgeInsets.all(AppSpacing.xxl), + child: context.isCompact + ? SingleChildScrollView( + child: Column(children: [ + _summary(txn), + const SizedBox(height: AppSpacing.lg), + SizedBox( + height: 480, + child: ReceiptPreview(transaction: txn), + ), + ]), + ) + : Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded(flex: 5, child: _summary(txn)), + const SizedBox(width: AppSpacing.xxl), + Expanded( + flex: 4, + child: ReceiptPreview(transaction: txn), + ), + ], + ), + ), + ), + ), + ); + } + + Widget _summary(SaleTransaction txn) { + return GlassCard( + padding: const EdgeInsets.all(AppSpacing.xxxl), + radius: AppRadius.xxl, + shadows: AppColors.shadowMd, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Center( + child: Container( + width: 84, + height: 84, + decoration: const BoxDecoration( + color: AppColors.successSurface, + shape: BoxShape.circle, + ), + child: const Icon(Icons.check_rounded, + size: 44, color: AppColors.success), + ) + .animate() + .scale( + duration: 340.ms, + curve: Curves.easeOutBack, + begin: const Offset(0.5, 0.5), + ) + .fadeIn(), + ), + const SizedBox(height: AppSpacing.xl), + Text('Sale complete', + textAlign: TextAlign.center, + style: context.text.headlineMedium), + const SizedBox(height: AppSpacing.xs), + Text( + '${txn.invoiceNumber} · ${Formatters.dateTime(txn.createdAt)}', + textAlign: TextAlign.center, + style: context.text.bodySmall, + ), + + const SizedBox(height: AppSpacing.xxl), + Container( + padding: const EdgeInsets.all(AppSpacing.xl), + decoration: BoxDecoration( + color: AppColors.primarySurface, + borderRadius: AppRadius.brLg, + ), + child: Column(children: [ + Text('Amount paid', style: context.text.labelMedium), + Text( + Formatters.money(txn.total), + style: AppTypography.money(36, color: AppColors.primary), + ), + const SizedBox(height: AppSpacing.md), + const Divider(), + const SizedBox(height: AppSpacing.md), + _row('Paid via', txn.paymentSummary), + if (txn.changeDue > 0) + _row('Change returned', Formatters.money(txn.changeDue), + highlight: AppColors.success), + _row('Items', '${txn.cart.lineCount}'), + if (txn.customer != null) ...[ + _row('Customer', txn.customer!.name), + _row('Points earned', '+${txn.pointsEarned}', + highlight: AppColors.success), + if (txn.pointsRedeemed > 0) + _row('Points redeemed', '-${txn.pointsRedeemed}'), + ], + if (txn.cart.totalSavings > 0) + _row( + 'Customer saved', + Formatters.money(txn.cart.totalSavings), + highlight: AppColors.success, + ), + ]), + ), + + const SizedBox(height: AppSpacing.xxl), + Row(children: [ + Expanded( + child: PrimaryButton( + label: 'Reprint', + icon: Icons.print_outlined, + tone: ButtonTone.neutral, + onPressed: () { + _cancelAutoReturn(); + ref.read(receiptServiceProvider).printWithDialog(txn); + }, + ), + ), + const SizedBox(width: AppSpacing.md), + Expanded( + child: PrimaryButton( + label: 'Share', + icon: Icons.ios_share_rounded, + tone: ButtonTone.neutral, + onPressed: () { + _cancelAutoReturn(); + ref.read(receiptServiceProvider).share(txn); + }, + ), + ), + ]), + const SizedBox(height: AppSpacing.md), + PrimaryButton( + label: _seconds > 0 + ? 'New Sale ($_seconds)' + : 'New Sale', + icon: Icons.add_shopping_cart_rounded, + large: true, + onPressed: _newSale, + ), + const SizedBox(height: AppSpacing.sm), + TextButton( + onPressed: _continueBilling, + child: const Text('Back to billing screen'), + ), + ], + ), + ); + } + + Widget _row(String label, String value, {Color? highlight}) => Padding( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(label, + style: const TextStyle( + fontSize: 13.5, + color: AppColors.textSecondary, + )), + Text( + value, + style: TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + color: highlight ?? AppColors.textPrimary, + ), + ), + ], + ), + ); +} diff --git a/lib/presentation/receipt/widgets/receipt_preview.dart b/lib/presentation/receipt/widgets/receipt_preview.dart new file mode 100644 index 0000000..fb9bbb4 --- /dev/null +++ b/lib/presentation/receipt/widgets/receipt_preview.dart @@ -0,0 +1,289 @@ +import 'package:flutter/material.dart'; + +import '../../../core/constants/app_constants.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../domain/entities/transaction.dart'; + +/// Paper-like preview of what the thermal printer produced. +class ReceiptPreview extends StatelessWidget { + const ReceiptPreview({super.key, required this.transaction}); + + final SaleTransaction transaction; + + @override + Widget build(BuildContext context) { + final txn = transaction; + final cart = txn.cart; + + return Container( + decoration: BoxDecoration( + color: AppColors.surface, + borderRadius: AppRadius.brLg, + boxShadow: AppColors.shadowMd, + ), + child: Column(children: [ + const _Perforation(top: true), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.xxl, + vertical: AppSpacing.xl, + ), + child: DefaultTextStyle( + style: AppTypography.mono(11.5, color: AppColors.textPrimary), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Center( + child: Column(children: [ + Text( + AppConstants.storeName.toUpperCase(), + style: AppTypography.mono(15) + .copyWith(fontWeight: FontWeight.w700), + ), + const SizedBox(height: 3), + Text(AppConstants.storeAddress, + textAlign: TextAlign.center, + style: AppTypography.mono(9.5)), + Text('GSTIN: ${AppConstants.storeGstin}', + style: AppTypography.mono(9.5)), + const SizedBox(height: AppSpacing.sm), + Text('TAX INVOICE', + style: AppTypography.mono(11.5) + .copyWith(fontWeight: FontWeight.w700)), + ]), + ), + + const _Dashes(), + _row('Invoice', txn.invoiceNumber), + _row('Date', Formatters.receiptStamp(txn.createdAt)), + _row('Cashier', txn.cashierName), + _row('Customer', txn.customer?.name ?? 'Walk-in'), + + const _Dashes(), + Row(children: [ + Expanded(flex: 5, child: _bold('Item')), + Expanded( + flex: 2, + child: _bold('Qty', align: TextAlign.center), + ), + Expanded( + flex: 3, + child: _bold('Amount', align: TextAlign.right), + ), + ]), + const SizedBox(height: AppSpacing.xs), + + ...cart.lines.map((line) => Padding( + padding: const EdgeInsets.symmetric(vertical: 2.5), + child: Row(children: [ + Expanded(flex: 5, child: Text(line.product.name)), + Expanded( + flex: 2, + child: Text( + line.quantity % 1 == 0 + ? line.quantity.toStringAsFixed(0) + : line.quantity.toStringAsFixed(2), + textAlign: TextAlign.center, + ), + ), + Expanded( + flex: 3, + child: Text( + line.payable.toStringAsFixed(2), + textAlign: TextAlign.right, + ), + ), + ]), + )), + + const _Dashes(), + _row('Subtotal', cart.subtotal.toStringAsFixed(2)), + if (cart.billDiscountTotal > 0) + _row('Discount', + '-${cart.billDiscountTotal.toStringAsFixed(2)}'), + if (cart.loyaltyRedemptionValue > 0) + _row('Points redeemed', + '-${cart.loyaltyRedemptionValue.toStringAsFixed(2)}'), + _row('CGST', cart.cgst.toStringAsFixed(2)), + _row('SGST', cart.sgst.toStringAsFixed(2)), + if (cart.roundOff != 0) + _row('Round off', cart.roundOff.toStringAsFixed(2)), + + const _Dashes(), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('TOTAL', + style: AppTypography.mono(15).copyWith( + fontWeight: FontWeight.w800, + color: AppColors.textPrimary, + )), + Text( + Formatters.money(txn.total), + style: AppTypography.mono(15).copyWith( + fontWeight: FontWeight.w800, + color: AppColors.textPrimary, + ), + ), + ], + ), + + const _Dashes(), + ...txn.payments.map((p) => + _row(p.method.label, p.amount.toStringAsFixed(2))), + if (txn.changeDue > 0) + _row('Change', txn.changeDue.toStringAsFixed(2)), + + if (txn.customer != null) ...[ + const _Dashes(), + _row('Points earned', '+${txn.pointsEarned}'), + _row('Membership', txn.customer!.tier.label), + ], + + const SizedBox(height: AppSpacing.lg), + Center( + child: Column(children: [ + _FakeBarcode(value: txn.invoiceNumber), + const SizedBox(height: AppSpacing.sm), + Text('Thank you for shopping with us!', + style: AppTypography.mono(11) + .copyWith(fontWeight: FontWeight.w700)), + const SizedBox(height: 2), + Text('Powered by Nearle POS', + style: AppTypography.mono(9)), + ]), + ), + ], + ), + ), + ), + ), + const _Perforation(top: false), + ]), + ); + } + + Widget _row(String label, String value) => Padding( + padding: const EdgeInsets.symmetric(vertical: 1.5), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [Text(label), Text(value)], + ), + ); + + Widget _bold(String text, {TextAlign align = TextAlign.left}) => Text( + text, + textAlign: align, + style: AppTypography.mono(11.5).copyWith( + fontWeight: FontWeight.w700, + color: AppColors.textPrimary, + ), + ); +} + +class _Dashes extends StatelessWidget { + const _Dashes(); + + @override + Widget build(BuildContext context) { + return const Padding( + padding: EdgeInsets.symmetric(vertical: AppSpacing.sm), + child: Text( + '- - - - - - - - - - - - - - - - - - - - - - - - - -', + maxLines: 1, + overflow: TextOverflow.clip, + style: TextStyle(color: AppColors.textTertiary, fontSize: 10), + ), + ); + } +} + +/// Zig-zag torn-paper edge. +class _Perforation extends StatelessWidget { + const _Perforation({required this.top}); + + final bool top; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: 10, + child: CustomPaint( + size: const Size(double.infinity, 10), + painter: _PerforationPainter(top: top), + ), + ); + } +} + +class _PerforationPainter extends CustomPainter { + const _PerforationPainter({required this.top}); + + final bool top; + + @override + void paint(Canvas canvas, Size size) { + const tooth = 12.0; + final path = Path(); + + if (top) { + path.moveTo(0, size.height); + for (var x = 0.0; x < size.width; x += tooth) { + path.lineTo(x + tooth / 2, 0); + path.lineTo(x + tooth, size.height); + } + path.lineTo(size.width, size.height); + } else { + path.moveTo(0, 0); + for (var x = 0.0; x < size.width; x += tooth) { + path.lineTo(x + tooth / 2, size.height); + path.lineTo(x + tooth, 0); + } + path.lineTo(size.width, 0); + } + path.close(); + + canvas.drawPath(path, Paint()..color = AppColors.surface); + } + + @override + bool shouldRepaint(covariant _PerforationPainter oldDelegate) => + oldDelegate.top != top; +} + +/// Decorative Code-128-style bar rendering for the preview only. +class _FakeBarcode extends StatelessWidget { + const _FakeBarcode({required this.value}); + + final String value; + + @override + Widget build(BuildContext context) { + final bars = value.codeUnits; + + return Column(children: [ + SizedBox( + height: 38, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + for (var i = 0; i < bars.length * 2; i++) + Container( + width: (bars[i ~/ 2] % 3 == 0) ? 3 : 1.5, + margin: const EdgeInsets.symmetric(horizontal: 0.7), + color: i.isEven + ? AppColors.textPrimary + : Colors.transparent, + ), + ], + ), + ), + const SizedBox(height: 3), + Text(value, style: AppTypography.mono(9)), + ]); + } +} diff --git a/lib/presentation/sync/providers/sync_controller.dart b/lib/presentation/sync/providers/sync_controller.dart new file mode 100644 index 0000000..1efcbd5 --- /dev/null +++ b/lib/presentation/sync/providers/sync_controller.dart @@ -0,0 +1,156 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../app/providers.dart'; +import '../../../domain/entities/shift_report.dart'; +import '../../../domain/entities/sync_event.dart'; +import '../../auth/providers/auth_controller.dart'; +import '../../pos/providers/catalog_providers.dart'; + +/// Progress of a catalogue pull. +sealed class ImportState { + const ImportState(); +} + +class ImportIdle extends ImportState { + const ImportIdle(); +} + +class ImportRunning extends ImportState { + const ImportRunning(this.progress, this.stage); + + final double progress; + final String stage; +} + +class ImportDone extends ImportState { + const ImportDone(this.event); + + final SyncEvent event; +} + +class ImportFailed extends ImportState { + const ImportFailed(this.message); + + final String message; +} + +/// Bumped after every successful import so catalogue providers refetch. +final catalogueVersionProvider = StateProvider((ref) => 0); + +/// Whether the terminal has products to sell. The POS is gated on this. +final catalogueReadyProvider = Provider((ref) { + ref.watch(catalogueVersionProvider); + return ref.watch(syncRepositoryProvider).hasCatalogue; +}); + +final lastImportAtProvider = Provider((ref) { + ref.watch(catalogueVersionProvider); + return ref.watch(syncRepositoryProvider).lastImportAt; +}); + +class CatalogueImportController extends StateNotifier { + CatalogueImportController(this._ref) : super(const ImportIdle()); + + final Ref _ref; + + Future run() async { + if (state is ImportRunning) return false; + + state = const ImportRunning(0, 'Starting…'); + + final event = await _ref.read(syncRepositoryProvider).importCatalogue( + onProgress: (progress, stage) { + if (mounted) state = ImportRunning(progress, stage); + }, + ); + + if (event.status == SyncStatus.synced) { + // Force every catalogue-backed provider to refetch. + _ref.read(catalogueVersionProvider.notifier).state++; + _ref.invalidate(allProductsProvider); + _ref.invalidate(visibleProductsProvider); + _ref.invalidate(categoryCountsProvider); + _ref.invalidate(lowStockProductsProvider); + + state = ImportDone(event); + return true; + } + + state = ImportFailed(event.error ?? 'Import failed.'); + return false; + } + + void reset() => state = const ImportIdle(); +} + +final catalogueImportProvider = + StateNotifierProvider( + (ref) => CatalogueImportController(ref), +); + +// ------------------------------------------------------------------ Events +/// Bumped whenever the event log changes. +final syncVersionProvider = StateProvider((ref) => 0); + +final syncEventsProvider = Provider>((ref) { + ref.watch(syncVersionProvider); + ref.watch(catalogueVersionProvider); + return ref.watch(syncRepositoryProvider).events; +}); + +final hasUnsyncedProvider = Provider((ref) { + ref.watch(syncVersionProvider); + ref.watch(catalogueVersionProvider); + return ref.watch(syncRepositoryProvider).hasUnsyncedEvents; +}); + +/// Today's takings, recomputed from local sales on every change. +final shiftReportProvider = Provider((ref) { + ref.watch(syncVersionProvider); + final session = ref.watch(cashierSessionProvider); + final user = ref.watch(currentUserProvider); + + return ref.watch(syncRepositoryProvider).buildShiftReport( + businessDate: DateTime.now(), + terminalId: session.terminalId, + cashierName: user?.name ?? session.name, + ); +}); + +/// Drives the push button and the sign-out dialog. +class ReportPushController extends StateNotifier { + ReportPushController(this._ref) : super(false); + + final Ref _ref; + + /// Pushes today's report. Returns the resulting event so the caller can + /// tell the cashier whether it landed. + Future pushToday() async { + state = true; + try { + final report = _ref.read(shiftReportProvider); + final event = + await _ref.read(syncRepositoryProvider).pushShiftReport(report); + _ref.read(syncVersionProvider.notifier).state++; + return event; + } finally { + if (mounted) state = false; + } + } + + Future retry(String eventId) async { + state = true; + try { + final event = await _ref.read(syncRepositoryProvider).retry(eventId); + _ref.read(syncVersionProvider.notifier).state++; + return event; + } finally { + if (mounted) state = false; + } + } +} + +final reportPushProvider = + StateNotifierProvider( + (ref) => ReportPushController(ref), +); diff --git a/lib/presentation/sync/widgets/sign_out_dialog.dart b/lib/presentation/sync/widgets/sign_out_dialog.dart new file mode 100644 index 0000000..2231b2f --- /dev/null +++ b/lib/presentation/sync/widgets/sign_out_dialog.dart @@ -0,0 +1,233 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/widgets/primary_button.dart'; +import '../../../domain/entities/sync_event.dart'; +import '../../auth/providers/auth_controller.dart'; +import '../../pos/providers/cart_controller.dart'; +import '../providers/sync_controller.dart'; + +/// End-of-shift flow. +/// +/// The day's takings are pushed here — the second and last moment this +/// terminal needs a connection. Signing out without pushing is allowed, but +/// the report stays queued locally rather than being discarded. +Future showSignOutDialog(BuildContext context, WidgetRef ref) { + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const _SignOutDialog(), + ); +} + +class _SignOutDialog extends ConsumerStatefulWidget { + const _SignOutDialog(); + + @override + ConsumerState<_SignOutDialog> createState() => _SignOutDialogState(); +} + +class _SignOutDialogState extends ConsumerState<_SignOutDialog> { + SyncEvent? _result; + + void _finish() { + ref.read(cartControllerProvider.notifier).reset(); + ref.read(authControllerProvider.notifier).signOut(); + Navigator.of(context).pop(); + context.go(AppRoutes.login); + } + + Future _pushThenFinish() async { + final event = await ref.read(reportPushProvider.notifier).pushToday(); + if (!mounted) return; + + setState(() => _result = event); + + if (event.status == SyncStatus.synced) { + await Future.delayed(const Duration(milliseconds: 700)); + if (mounted) _finish(); + } + } + + @override + Widget build(BuildContext context) { + final report = ref.watch(shiftReportProvider); + final cart = ref.watch(cartControllerProvider); + final pushing = ref.watch(reportPushProvider); + final failed = _result?.status == SyncStatus.failed; + + return AlertDialog( + title: const Text('End shift'), + contentPadding: const EdgeInsets.fromLTRB( + AppSpacing.xxl, + AppSpacing.lg, + AppSpacing.xxl, + AppSpacing.sm, + ), + content: SizedBox( + width: 420, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (cart.isNotEmpty) + _Banner( + icon: Icons.warning_amber_rounded, + color: AppColors.warning, + background: AppColors.warningSurface, + message: 'The current bill has ${cart.lineCount} item(s) ' + 'and will be cleared. Park it first if you need it.', + ), + + if (report.isEmpty) + const _Banner( + icon: Icons.info_outline_rounded, + color: AppColors.textSecondary, + background: AppColors.surfaceAlt, + message: 'No sales were recorded today, so there is nothing ' + 'to push.', + ) + else ...[ + const Text( + "Today's takings", + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: AppColors.textSecondary, + ), + ), + const SizedBox(height: AppSpacing.sm), + _row('Bills', '${report.billCount}'), + _row('Items sold', report.itemCount.toStringAsFixed(0)), + _row('Gross sales', Formatters.money(report.grossSales)), + _row('GST collected', Formatters.money(report.taxCollected)), + _row('Average basket', + Formatters.money(report.averageBasket)), + ], + + if (failed) ...[ + const SizedBox(height: AppSpacing.md), + _Banner( + icon: Icons.wifi_off_rounded, + color: AppColors.danger, + background: AppColors.dangerSurface, + message: _result?.error ?? + 'The push failed. The report is still saved on this ' + 'terminal and can be retried from Events.', + ), + ], + ], + ), + ), + ), + actionsPadding: const EdgeInsets.fromLTRB( + AppSpacing.xxl, + 0, + AppSpacing.xxl, + AppSpacing.lg, + ), + actions: [ + // Wrap keeps three actions from overflowing a narrow dialog. + Wrap( + alignment: WrapAlignment.end, + spacing: AppSpacing.sm, + runSpacing: AppSpacing.sm, + children: [ + TextButton( + onPressed: pushing ? null : () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + TextButton( + onPressed: pushing ? null : _finish, + style: TextButton.styleFrom( + foregroundColor: AppColors.textSecondary, + ), + child: Text( + report.isEmpty ? 'Sign out' : 'Sign out without pushing', + ), + ), + if (!report.isEmpty) + SizedBox( + width: 190, + child: PrimaryButton( + label: failed ? 'Retry push' : 'Push & sign out', + icon: Icons.cloud_upload_rounded, + busy: pushing, + onPressed: _pushThenFinish, + ), + ), + ], + ), + ], + ); + } + + Widget _row(String label, String value) => Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + children: [ + Expanded( + child: Text( + label, + style: const TextStyle( + fontSize: 13.5, + color: AppColors.textSecondary, + ), + ), + ), + Text( + value, + style: const TextStyle( + fontSize: 13.5, + fontWeight: FontWeight.w700, + ), + ), + ], + ), + ); +} + +class _Banner extends StatelessWidget { + const _Banner({ + required this.icon, + required this.color, + required this.background, + required this.message, + }); + + final IconData icon; + final Color color; + final Color background; + final String message; + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.only(bottom: AppSpacing.md), + padding: const EdgeInsets.all(AppSpacing.md), + decoration: BoxDecoration( + color: background, + borderRadius: AppRadius.brSm, + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, size: 18, color: color), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Text( + message, + style: TextStyle(fontSize: 12.5, color: color, height: 1.45), + ), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/welcome/screens/welcome_screen.dart b/lib/presentation/welcome/screens/welcome_screen.dart new file mode 100644 index 0000000..c554903 --- /dev/null +++ b/lib/presentation/welcome/screens/welcome_screen.dart @@ -0,0 +1,337 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_animate/flutter_animate.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../app/providers.dart'; +import '../../../core/constants/app_constants.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/utils/extensions.dart'; +import '../../../core/utils/formatters.dart'; +import '../../../core/widgets/glass_card.dart'; +import '../../pos/providers/cart_controller.dart'; +import '../widgets/welcome_illustration.dart'; + +/// Screen 1 — the terminal's resting state between sales. +class WelcomeScreen extends ConsumerWidget { + const WelcomeScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final session = ref.watch(cashierSessionProvider); + final clock = ref.watch(clockProvider).value ?? DateTime.now(); + + return Scaffold( + body: Container( + decoration: const BoxDecoration(gradient: AppColors.primaryGradient), + child: SafeArea( + child: Column( + children: [ + _TopBar(cashier: session.name, now: clock), + Expanded( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(AppSpacing.xxl), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 920), + child: GlassCard( + blur: 18, + padding: EdgeInsets.all( + context.responsive( + compact: AppSpacing.xxl, + expanded: AppSpacing.giant, + ), + ), + radius: AppRadius.xxl, + shadows: AppColors.shadowLg, + child: context.isCompact + ? const _StackedLayout() + : const _SideBySideLayout(), + ), + ), + ).animate().fadeIn(duration: 350.ms).slideY( + begin: 0.04, + end: 0, + curve: Curves.easeOutCubic, + ), + ), + ), + const _BottomHint(), + ], + ), + ), + ), + ); + } +} + +class _SideBySideLayout extends StatelessWidget { + const _SideBySideLayout(); + + @override + Widget build(BuildContext context) { + return Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: const [ + Expanded(flex: 4, child: WelcomeIllustration(size: 260)), + SizedBox(width: AppSpacing.giant), + Expanded(flex: 5, child: _WelcomeContent()), + ], + ); + } +} + +class _StackedLayout extends StatelessWidget { + const _StackedLayout(); + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + children: const [ + WelcomeIllustration(size: 150), + SizedBox(height: AppSpacing.xxl), + _WelcomeContent(), + ], + ); + } +} + +class _WelcomeContent extends ConsumerWidget { + const _WelcomeContent(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Welcome to', + style: context.text.titleMedium?.copyWith( + color: AppColors.textSecondary, + letterSpacing: 1.4, + ), + ), + const SizedBox(height: AppSpacing.xs), + Text( + 'Nearle POS', + style: context.text.displaySmall?.copyWith( + color: AppColors.primary, + fontWeight: FontWeight.w800, + ), + ), + const SizedBox(height: AppSpacing.md), + Text( + 'Start a new sale by identifying the shopper, ' + 'or skip straight to billing.', + style: context.text.bodyMedium + ?.copyWith(color: AppColors.textSecondary), + ), + const SizedBox(height: AppSpacing.xxxl), + + _WelcomeAction( + icon: Icons.person_add_alt_1_rounded, + title: 'New Customer', + subtitle: 'Register and start earning loyalty points', + onTap: () => context.push(AppRoutes.registerCustomer), + primary: true, + ), + const SizedBox(height: AppSpacing.md), + _WelcomeAction( + icon: Icons.badge_outlined, + title: 'Existing Customer', + subtitle: 'Look up by mobile number', + onTap: () => context.push(AppRoutes.existingCustomer), + ), + const SizedBox(height: AppSpacing.md), + _WelcomeAction( + icon: Icons.directions_walk_rounded, + title: 'Skip Customer', + subtitle: 'Walk-in sale, no loyalty tracking', + onTap: () { + ref.read(cartControllerProvider.notifier).reset(); + context.go(AppRoutes.pos); + }, + ), + ], + ); + } +} + +/// A tall, unmistakable target — the cashier taps this hundreds of times a day. +class _WelcomeAction extends StatefulWidget { + const _WelcomeAction({ + required this.icon, + required this.title, + required this.subtitle, + required this.onTap, + this.primary = false, + }); + + final IconData icon; + final String title; + final String subtitle; + final VoidCallback onTap; + final bool primary; + + @override + State<_WelcomeAction> createState() => _WelcomeActionState(); +} + +class _WelcomeActionState extends State<_WelcomeAction> { + bool _hovered = false; + + @override + Widget build(BuildContext context) { + final bg = widget.primary + ? AppColors.primary + : (_hovered ? AppColors.primarySurface : AppColors.surface); + final fg = + widget.primary ? AppColors.textOnPrimary : AppColors.textPrimary; + final sub = widget.primary + ? AppColors.textOnPrimary.withValues(alpha: 0.78) + : AppColors.textSecondary; + + return MouseRegion( + onEnter: (_) => setState(() => _hovered = true), + onExit: (_) => setState(() => _hovered = false), + child: AnimatedContainer( + duration: AppMotion.fast, + transform: Matrix4.translationValues(0, _hovered ? -2 : 0, 0), + child: Material( + color: bg, + borderRadius: AppRadius.brLg, + child: InkWell( + onTap: widget.onTap, + borderRadius: AppRadius.brLg, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.xl, + vertical: AppSpacing.lg, + ), + decoration: BoxDecoration( + borderRadius: AppRadius.brLg, + border: Border.all( + color: widget.primary + ? Colors.transparent + : AppColors.border, + ), + boxShadow: widget.primary && _hovered + ? AppColors.shadowMd + : null, + ), + child: Row( + children: [ + Container( + width: 46, + height: 46, + decoration: BoxDecoration( + color: widget.primary + ? Colors.white.withValues(alpha: 0.18) + : AppColors.primarySurface, + borderRadius: AppRadius.brMd, + ), + child: Icon( + widget.icon, + color: widget.primary + ? AppColors.textOnPrimary + : AppColors.primary, + size: 22, + ), + ), + const SizedBox(width: AppSpacing.lg), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.title, + style: context.text.titleMedium?.copyWith(color: fg), + ), + const SizedBox(height: 2), + Text( + widget.subtitle, + style: context.text.bodySmall?.copyWith(color: sub), + ), + ], + ), + ), + Icon(Icons.arrow_forward_rounded, color: sub, size: 20), + ], + ), + ), + ), + ), + ), + ); + } +} + +class _TopBar extends StatelessWidget { + const _TopBar({required this.cashier, required this.now}); + + final String cashier; + final DateTime now; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.xxl, + vertical: AppSpacing.lg, + ), + child: Row( + children: [ + const Icon(Icons.storefront_rounded, + color: Colors.white, size: 26), + const SizedBox(width: AppSpacing.md), + Text( + AppConstants.storeName, + style: context.text.titleLarge?.copyWith(color: Colors.white), + ), + const Spacer(), + Text( + '${Formatters.date(now)} ${Formatters.time(now)}', + style: context.text.bodyMedium + ?.copyWith(color: Colors.white.withValues(alpha: 0.85)), + ), + const SizedBox(width: AppSpacing.xxl), + CircleAvatar( + radius: 16, + backgroundColor: Colors.white.withValues(alpha: 0.2), + child: Text( + Formatters.initials(cashier), + style: const TextStyle( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.w700, + ), + ), + ), + const SizedBox(width: AppSpacing.sm), + Text(cashier, + style: context.text.bodyMedium?.copyWith(color: Colors.white)), + ], + ), + ); + } +} + +class _BottomHint extends StatelessWidget { + const _BottomHint(); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: AppSpacing.xl), + child: Text( + 'Scan a barcode at any time to begin a walk-in sale', + style: context.text.bodySmall + ?.copyWith(color: Colors.white.withValues(alpha: 0.7)), + ), + ); + } +} diff --git a/lib/presentation/welcome/widgets/welcome_illustration.dart b/lib/presentation/welcome/widgets/welcome_illustration.dart new file mode 100644 index 0000000..0b3f533 --- /dev/null +++ b/lib/presentation/welcome/widgets/welcome_illustration.dart @@ -0,0 +1,156 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_animate/flutter_animate.dart'; + +import '../../../core/theme/app_colors.dart'; + +/// Vector shopping-cart illustration drawn in code. +/// +/// Painting it avoids shipping a raster asset and keeps it crisp on 4K desktop +/// displays as well as tablet screens. +class WelcomeIllustration extends StatelessWidget { + const WelcomeIllustration({super.key, this.size = 240}); + + final double size; + + @override + Widget build(BuildContext context) { + return SizedBox( + width: size, + height: size, + child: CustomPaint(painter: _CartPainter()), + ) + .animate(onPlay: (c) => c.repeat(reverse: true)) + .moveY(begin: 0, end: -8, duration: 2400.ms, curve: Curves.easeInOut); + } +} + +class _CartPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final w = size.width; + final h = size.height; + final unit = w / 100; + + // Soft backdrop disc. + canvas.drawCircle( + Offset(w * 0.5, h * 0.5), + w * 0.46, + Paint()..color = AppColors.primarySurface, + ); + + // Decorative arc. + canvas.drawArc( + Rect.fromCircle(center: Offset(w * 0.5, h * 0.5), radius: w * 0.46), + -1.1, + 2.0, + false, + Paint() + ..color = AppColors.primaryBorder + ..style = PaintingStyle.stroke + ..strokeWidth = unit * 1.6 + ..strokeCap = StrokeCap.round, + ); + + final stroke = Paint() + ..color = AppColors.primary + ..style = PaintingStyle.stroke + ..strokeWidth = unit * 3 + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round; + + final fill = Paint()..color = AppColors.primary.withValues(alpha: 0.16); + + // Cart basket. + final basket = Path() + ..moveTo(w * 0.30, h * 0.36) + ..lineTo(w * 0.78, h * 0.36) + ..lineTo(w * 0.70, h * 0.60) + ..lineTo(w * 0.37, h * 0.60) + ..close(); + canvas.drawPath(basket, fill); + canvas.drawPath(basket, stroke); + + // Handle running to the push bar. + canvas.drawPath( + Path() + ..moveTo(w * 0.16, h * 0.26) + ..lineTo(w * 0.24, h * 0.26) + ..lineTo(w * 0.30, h * 0.36), + stroke, + ); + + // Basket ribs. + for (var i = 1; i <= 2; i++) { + final t = i / 3; + canvas.drawLine( + Offset(w * (0.30 + 0.48 * t), h * 0.36), + Offset(w * (0.37 + 0.33 * t), h * 0.60), + stroke..strokeWidth = unit * 1.6, + ); + } + stroke.strokeWidth = unit * 3; + + // Wheels. + for (final dx in [0.44, 0.66]) { + canvas.drawCircle( + Offset(w * dx, h * 0.70), + unit * 5, + Paint()..color = AppColors.surface, + ); + canvas.drawCircle(Offset(w * dx, h * 0.70), unit * 5, stroke); + } + + // Groceries poking out of the basket. + _item(canvas, Offset(w * 0.42, h * 0.30), unit * 5.5, + AppColors.tierGold.withValues(alpha: 0.9)); + _item(canvas, Offset(w * 0.55, h * 0.27), unit * 6.5, + AppColors.success.withValues(alpha: 0.85)); + _item(canvas, Offset(w * 0.67, h * 0.31), unit * 5, + AppColors.danger.withValues(alpha: 0.75)); + + // Receipt tape drifting away from the terminal. + final receipt = Path() + ..moveTo(w * 0.80, h * 0.20) + ..lineTo(w * 0.94, h * 0.20) + ..lineTo(w * 0.94, h * 0.44) + ..lineTo(w * 0.905, h * 0.40) + ..lineTo(w * 0.87, h * 0.44) + ..lineTo(w * 0.835, h * 0.40) + ..lineTo(w * 0.80, h * 0.44) + ..close(); + canvas.drawPath(receipt, Paint()..color = AppColors.surface); + canvas.drawPath( + receipt, + Paint() + ..color = AppColors.primaryLight + ..style = PaintingStyle.stroke + ..strokeWidth = unit * 1.4 + ..strokeJoin = StrokeJoin.round, + ); + + // Receipt lines. + final line = Paint() + ..color = AppColors.primaryBorder + ..strokeWidth = unit * 1.2 + ..strokeCap = StrokeCap.round; + for (var i = 0; i < 3; i++) { + final y = h * (0.25 + i * 0.05); + canvas.drawLine(Offset(w * 0.835, y), Offset(w * 0.905, y), line); + } + } + + void _item(Canvas canvas, Offset center, double radius, Color color) { + canvas.drawCircle(center, radius, Paint()..color = color); + canvas.drawCircle( + center, + radius, + Paint() + ..color = Colors.white.withValues(alpha: 0.5) + ..style = PaintingStyle.stroke + ..strokeWidth = 1.5, + ); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} 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..a1b075e --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +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 "nearle_pos") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.nearle_pos") + +# 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) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/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..eee4585 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,19 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin"); + audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar); + g_autoptr(FlPluginRegistrar) printing_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "PrintingPlugin"); + printing_plugin_register_with_registrar(printing_registrar); +} 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..8e3966a --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + audioplayers_linux + printing +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +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/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +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} + "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 preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/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/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..e383bf9 --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#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) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// 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, "nearle_pos"); + 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, "nearle_pos"); + } + + gtk_window_set_default_size(window, 1280, 720); + + 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); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(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 GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// 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_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#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..6064afd --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import audioplayers_darwin +import printing + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin")) + PrintingPlugin.register(with: registry.registrar(forPlugin: "PrintingPlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..b754503 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,729 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* nearle_pos.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "nearle_pos.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 = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* nearle_pos.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* nearle_pos.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.nearlePos.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/nearle_pos.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/nearle_pos"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.nearlePos.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/nearle_pos.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/nearle_pos"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.nearlePos.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/nearle_pos.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/nearle_pos"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + 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; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + 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.15; + 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; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + 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; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + 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.15; + 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; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + 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; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + 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.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency 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..629ab7e --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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..b3c1761 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: 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..82b6f9d 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..13b35eb 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..0a3f5fa 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..bdb5722 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..f083318 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..326c0e7 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..2f1632c 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..a299977 --- /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 = nearle_pos + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.nearlePos + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. 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..3cc05eb --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/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/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..0ba1763 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,682 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + archive: + dependency: transitive + description: + name: archive + sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff + url: "https://pub.dev" + source: hosted + version: "4.0.9" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + audioplayers: + dependency: "direct main" + description: + name: audioplayers + sha256: "2ba4bb2944baacbdd5372ff8254a8e7feb8c10d7739545e392f5605a8f618745" + url: "https://pub.dev" + source: hosted + version: "6.8.1" + audioplayers_android: + dependency: transitive + description: + name: audioplayers_android + sha256: f5ff5b15620fbab8cb0849e9636c48e2b96c3f0f71723bbbe2ad3c761b205f05 + url: "https://pub.dev" + source: hosted + version: "5.3.0" + audioplayers_darwin: + dependency: transitive + description: + name: audioplayers_darwin + sha256: "1ca553add991384ecf421b9569da850f3ab2472ffb83f6970b0416365abc51be" + url: "https://pub.dev" + source: hosted + version: "6.5.0" + audioplayers_linux: + dependency: transitive + description: + name: audioplayers_linux + sha256: "15178b726b7cdee5364d0463c8d445630c4e0fb7d26612b73c767e7d25de9417" + url: "https://pub.dev" + source: hosted + version: "4.3.0" + audioplayers_platform_interface: + dependency: transitive + description: + name: audioplayers_platform_interface + sha256: "765f6f0e6dca55cb471c9483fc77700564b3484d19198aca4ebb5147c6c85acb" + url: "https://pub.dev" + source: hosted + version: "7.2.0" + audioplayers_web: + dependency: transitive + description: + name: audioplayers_web + sha256: ae1e0103c865a03e273f6d13d97b93f5595eac09915729cd5e37ef96e2857319 + url: "https://pub.dev" + source: hosted + version: "5.3.0" + audioplayers_windows: + dependency: transitive + description: + name: audioplayers_windows + sha256: a70ae82bba2dfcb6eb03dd4815d737a2d46d33ea5a96a03f535cfcaac490e413 + url: "https://pub.dev" + source: hosted + version: "4.4.1" + barcode: + dependency: transitive + description: + name: barcode + sha256: "7b6729c37e3b7f34233e2318d866e8c48ddb46c1f7ad01ff7bb2a8de1da2b9f4" + url: "https://pub.dev" + source: hosted + version: "2.2.9" + bidi: + dependency: transitive + description: + name: bidi + sha256: "77f475165e94b261745cf1032c751e2032b8ed92ccb2bf5716036db79320637d" + url: "https://pub.dev" + source: hosted + version: "2.0.13" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + equatable: + dependency: "direct main" + description: + name: equatable + sha256: "3bce007a596ff8b3119c45d68aaef631272537c03d30e5d4534dd24bf4c5eaa2" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_animate: + dependency: "direct main" + description: + name: flutter_animate + sha256: "7befe2d3252728afb77aecaaea1dec88a89d35b9b1d2eea6d04479e8af9117b5" + url: "https://pub.dev" + source: hosted + version: "4.5.2" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "9532ee6db4a943a1ed8383072a2e3eeda041db5657cdf6d2acecf3c21ecbe7e1" + url: "https://pub.dev" + source: hosted + version: "2.6.1" + flutter_shaders: + dependency: transitive + description: + name: flutter_shaders + sha256: "34794acadd8275d971e02df03afee3dee0f98dbfb8c4837082ad0034f612a3e2" + url: "https://pub.dev" + source: hosted + version: "0.1.3" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + go_router: + dependency: "direct main" + description: + name: go_router + sha256: f02fd7d2a4dc512fec615529824fdd217fecb3a3d3de68360293a551f21634b3 + url: "https://pub.dev" + source: hosted + version: "14.8.1" + google_fonts: + dependency: "direct main" + description: + name: google_fonts + sha256: ba03d03bcaa2f6cb7bd920e3b5027181db75ab524f8891c8bc3aa603885b8055 + url: "https://pub.dev" + source: hosted + version: "6.3.3" + hooks: + dependency: transitive + description: + name: hooks + sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: "6300175e00616bbc832e2fc91bfa4d776af5402c81c7151bee6905bb08473c52" + url: "https://pub.dev" + source: hosted + version: "4.9.1" + intl: + dependency: "direct main" + description: + name: intl + sha256: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf + url: "https://pub.dev" + source: hosted + version: "0.19.0" + jni: + dependency: transitive + description: + name: jni + sha256: "5bc9a9daac5ccfbd6a758377600b9f7fdce13d93f26e8012a8941014a5d978d1" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "7b717011ea40d04fd47c2731d3d1d36eb99eba3435c2753d62489e8c3c9991d5" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + jni_util: + dependency: transitive + description: + name: jni_util + sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + url: "https://pub.dev" + source: hosted + version: "0.12.19" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" + url: "https://pub.dev" + source: hosted + version: "1.18.0" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e + url: "https://pub.dev" + source: hosted + version: "9.5.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d + url: "https://pub.dev" + source: hosted + version: "3.0.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_parsing: + dependency: transitive + description: + name: path_parsing + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 + url: "https://pub.dev" + source: hosted + version: "2.1.6" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + pdf: + dependency: "direct main" + description: + name: pdf + sha256: "517df47af468734a23c8b513c0c6a8a62357403ab1b8ab7fad1606576a9dbdd0" + url: "https://pub.dev" + source: hosted + version: "3.13.0" + pdf_widget_wrapper: + dependency: transitive + description: + name: pdf_widget_wrapper + sha256: c930860d987213a3d58c7ec3b7ecf8085c3897f773e8dc23da9cae60a5d6d0f5 + url: "https://pub.dev" + source: hosted + version: "1.0.4" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + posix: + dependency: transitive + description: + name: posix + sha256: bc1bad54ad2b735816e31f8d4600cfde6c7839975085ddfbca48b6c9f7c4044e + url: "https://pub.dev" + source: hosted + version: "6.5.2" + printing: + dependency: "direct main" + description: + name: printing + sha256: f6cd14c768c1352dd37a958a3ee351aa9ce305b398218d3acd86389d5f7ecad1 + url: "https://pub.dev" + source: hosted + version: "5.15.0" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + qr: + dependency: transitive + description: + name: qr + sha256: "5a1d2586170e172b8a8c8470bbbffd5eb0cd38a66c0d77155ea138d3af3a4445" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: "59062512288d3056b2321804332a13ffdd1bf16df70dcc8e506e411280a72959" + url: "https://pub.dev" + source: hosted + version: "2.6.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + state_notifier: + dependency: transitive + description: + name: state_notifier + sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb + url: "https://pub.dev" + source: hosted + version: "1.0.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: "61894a1956de6b4fc1aefd0892e109514a1a706cbece3ac59decd90ff5a7a423" + url: "https://pub.dev" + source: hosted + version: "3.4.1+1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" + url: "https://pub.dev" + source: hosted + version: "0.7.11" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + uuid: + dependency: "direct main" + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.dev" + source: hosted + version: "4.6.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + url: "https://pub.dev" + source: hosted + version: "15.2.0" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4" + url: "https://pub.dev" + source: hosted + version: "7.0.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.12.0 <4.0.0" + flutter: ">=3.44.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..c93f580 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,43 @@ +name: nearle_pos +description: Nearle POS — enterprise Point of Sale for supermarkets, grocery, pharmacy and retail. +publish_to: "none" +version: 1.0.0+1 + +environment: + sdk: ">=3.6.0 <4.0.0" + +dependencies: + flutter: + sdk: flutter + + # State management + flutter_riverpod: ^2.5.1 + + # Routing + go_router: ^14.2.0 + + # Value equality for domain entities + equatable: ^2.0.5 + + # Formatting & ids + intl: ^0.19.0 + uuid: ^4.4.0 + + # UI + google_fonts: ^6.2.1 + flutter_animate: ^4.5.0 + + # Peripherals: scanner beeps and thermal receipt printing + audioplayers: ^6.0.0 + pdf: ^3.11.0 + printing: ^5.13.0 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^4.0.0 + +flutter: + uses-material-design: true + assets: + - assets/sounds/ diff --git a/test/unit/cart_test.dart b/test/unit/cart_test.dart new file mode 100644 index 0000000..942ecff --- /dev/null +++ b/test/unit/cart_test.dart @@ -0,0 +1,248 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:nearle_pos/domain/entities/cart.dart'; +import 'package:nearle_pos/domain/entities/customer.dart'; +import 'package:nearle_pos/domain/entities/product.dart'; + +/// Plain 18% GST item priced at a round number so expected values stay exact. +const _item = Product( + id: 'test-1', + name: 'Test Item', + barcode: '8900000000001', + sku: 'TST-001', + category: ProductCategory.grocery, + price: 100, + stock: 50, + gstRate: 0.18, +); + +Customer _silver() => Customer( + id: 'cust-1', + name: 'Silver Shopper', + mobile: '9876543210', + loyaltyPoints: 320, + // Above the 10,000 silver threshold, below the 50,000 gold one. + lifetimeSpend: 24500, + ); + +void main() { + group('Discount', () { + test('percentage resolves against the base', () { + const d = Discount(type: DiscountType.percentage, value: 10); + expect(d.amountOn(200), 20); + }); + + test('flat discount never exceeds the base', () { + const d = Discount(type: DiscountType.flat, value: 500); + expect(d.amountOn(200), 200); + }); + + test('none is inactive and worth nothing', () { + expect(Discount.none.isActive, isFalse); + expect(Discount.none.amountOn(200), 0); + }); + }); + + group('CartLine', () { + test('splits GST out of a tax-inclusive price', () { + const line = CartLine(product: _item, quantity: 2); + + expect(line.grossAmount, 200); + expect(line.payable, 200); + // 200 / 1.18 = 169.4915... -> 169.49 + expect(line.taxableValue, 169.49); + expect(line.taxAmount, 30.51); + expect(line.cgst + line.sgst, closeTo(line.taxAmount, 0.01)); + }); + + test('line discount reduces the payable', () { + const line = CartLine( + product: _item, + quantity: 2, + discount: Discount(type: DiscountType.percentage, value: 10), + ); + + expect(line.discountAmount, 20); + expect(line.payable, 180); + }); + + test('flags a quantity beyond available stock', () { + const ok = CartLine(product: _item, quantity: 50); + const over = CartLine(product: _item, quantity: 51); + + expect(ok.exceedsStock, isFalse); + expect(over.exceedsStock, isTrue); + }); + }); + + group('Cart totals', () { + test('empty cart is all zeroes', () { + const cart = Cart.empty; + + expect(cart.isEmpty, isTrue); + expect(cart.subtotal, 0); + expect(cart.grandTotal, 0); + expect(cart.pointsEarned, 0); + }); + + test('sums lines into a subtotal', () { + const cart = Cart(lines: [CartLine(product: _item, quantity: 2)]); + + expect(cart.lineCount, 1); + expect(cart.totalQuantity, 2); + expect(cart.subtotal, 200); + expect(cart.grandTotal, 200); + expect(cart.roundOff, 0); + }); + + test('rounds the payable to the nearest rupee', () { + const odd = Product( + id: 'test-2', + name: 'Odd Price', + barcode: '8900000000002', + sku: 'TST-002', + category: ProductCategory.grocery, + price: 99.99, + stock: 10, + ); + const cart = Cart(lines: [CartLine(product: odd, quantity: 1)]); + + expect(cart.netAmount, 99.99); + expect(cart.grandTotal, 100); + expect(cart.roundOff, closeTo(0.01, 0.001)); + }); + + test('applies the membership discount automatically', () { + final cart = Cart( + lines: const [CartLine(product: _item, quantity: 2)], + customer: _silver(), + ); + + expect(cart.customer!.tier, MembershipTier.silver); + // Silver is 2% off 200. + expect(cart.membershipDiscountAmount, 4); + expect(cart.netAmount, 196); + expect(cart.grandTotal, 196); + }); + + test('walk-in bills get no membership discount', () { + const cart = Cart(lines: [CartLine(product: _item, quantity: 2)]); + + expect(cart.isWalkIn, isTrue); + expect(cart.membershipDiscountAmount, 0); + expect(cart.grandTotal, 200); + }); + + test('stacks a manual discount on top of the membership one', () { + final cart = Cart( + lines: const [CartLine(product: _item, quantity: 2)], + customer: _silver(), + billDiscount: const Discount(type: DiscountType.flat, value: 16), + ); + + // 4 (silver) + 16 (manual) = 20 off 200. + expect(cart.billDiscountTotal, 20); + expect(cart.grandTotal, 180); + }); + + test('apportions bill-level discounts across the GST charged', () { + final full = Cart( + lines: const [CartLine(product: _item, quantity: 2)], + customer: _silver(), + ); + + // Bill fell to 98% of subtotal, so GST should fall in step. + expect(full.taxAmount, closeTo(30.51 * 0.98, 0.02)); + expect(full.taxableAmount, closeTo(full.netAmount - full.taxAmount, 0.01)); + }); + + test('breaks GST out by slab', () { + const zeroRated = Product( + id: 'test-3', + name: 'Onion 1kg', + barcode: '8900000000003', + sku: 'TST-003', + category: ProductCategory.vegetables, + price: 35, + stock: 20, + gstRate: 0, + ); + const cart = Cart(lines: [ + CartLine(product: _item, quantity: 1), + CartLine(product: zeroRated, quantity: 1), + ]); + + final breakdown = cart.taxBreakdown; + expect(breakdown.keys, containsAll([0.18, 0.0])); + expect(breakdown[0.0], 0); + expect(breakdown[0.18]!, greaterThan(0)); + }); + }); + + group('Loyalty', () { + test('earns one point per ten rupees, floored', () { + final cart = Cart( + lines: const [CartLine(product: _item, quantity: 2)], + customer: _silver(), + ); + + // Grand total 196 -> 19 points. + expect(cart.grandTotal, 196); + expect(cart.pointsEarned, 19); + }); + + test('caps redemption at the point balance', () { + final cart = Cart( + lines: const [CartLine(product: _item, quantity: 2)], + customer: _silver(), + ); + + // 320 points held; the bill could absorb far more. + expect(cart.maxRedeemablePoints, 320); + }); + + test('redeemed points come off the payable at 25 paise each', () { + final cart = Cart( + lines: const [CartLine(product: _item, quantity: 2)], + customer: _silver(), + pointsRedeemed: 320, + ); + + expect(cart.loyaltyRedemptionValue, 80); + // 200 - 4 (silver) - 80 (points) = 116. + expect(cart.netAmount, 116); + expect(cart.grandTotal, 116); + }); + + test('a walk-in can never redeem', () { + const cart = Cart(lines: [CartLine(product: _item, quantity: 2)]); + expect(cart.maxRedeemablePoints, 0); + }); + + test('the payable can never go below zero', () { + final cart = Cart( + lines: const [CartLine(product: _item, quantity: 1)], + customer: _silver(), + billDiscount: const Discount(type: DiscountType.flat, value: 9999), + ); + + expect(cart.netAmount, 0); + expect(cart.grandTotal, 0); + }); + }); + + group('MembershipTier', () { + test('maps lifetime spend onto the right tier', () { + expect(MembershipTier.forSpend(0), MembershipTier.bronze); + expect(MembershipTier.forSpend(9999), MembershipTier.bronze); + expect(MembershipTier.forSpend(10000), MembershipTier.silver); + expect(MembershipTier.forSpend(50000), MembershipTier.gold); + expect(MembershipTier.forSpend(150000), MembershipTier.platinum); + expect(MembershipTier.forSpend(999999), MembershipTier.platinum); + }); + + test('platinum is the ceiling', () { + expect(MembershipTier.platinum.next, isNull); + expect(MembershipTier.bronze.next, MembershipTier.silver); + }); + }); +} diff --git a/test/unit/checkout_test.dart b/test/unit/checkout_test.dart new file mode 100644 index 0000000..f68bd72 --- /dev/null +++ b/test/unit/checkout_test.dart @@ -0,0 +1,254 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:nearle_pos/data/datasources/local_store.dart'; +import 'package:nearle_pos/data/repositories/customer_repository_impl.dart'; +import 'package:nearle_pos/data/repositories/product_repository_impl.dart'; +import 'package:nearle_pos/data/repositories/transaction_repository_impl.dart'; +import 'package:nearle_pos/domain/entities/cart.dart'; +import 'package:nearle_pos/domain/entities/customer.dart'; +import 'package:nearle_pos/domain/entities/transaction.dart'; +import 'package:nearle_pos/domain/usecases/checkout_sale.dart'; + +void main() { + late LocalStore store; + late ProductRepositoryImpl products; + late CustomerRepositoryImpl customers; + late TransactionRepositoryImpl transactions; + late CheckoutSale checkout; + + setUp(() async { + store = LocalStore.instance; + // Fresh seed for every test so stock and invoice sequence never leak. + await store.reset(); + + products = ProductRepositoryImpl(store); + customers = CustomerRepositoryImpl(store); + transactions = TransactionRepositoryImpl(store); + checkout = CheckoutSale( + productRepository: products, + customerRepository: customers, + transactionRepository: transactions, + ); + }); + + /// Amul Milk 1L: 62.00, 5% GST, 50 in stock. + Future milkCart({int qty = 2, String? customerId}) async { + final milk = (await products.findByBarcode('8901234500011'))!; + final customer = + customerId == null ? null : await customers.findById(customerId); + return Cart( + lines: [CartLine(product: milk, quantity: qty.toDouble())], + customer: customer, + ); + } + + group('successful checkout', () { + test('records the sale and returns an invoice', () async { + final cart = await milkCart(); + expect(cart.grandTotal, 124); + + final result = await checkout( + cart: cart, + payments: const [ + PaymentSplit(method: PaymentMethod.cash, amount: 124, tendered: 200), + ], + cashierName: 'Suriya', + ); + + final txn = result.transaction; + expect(txn.total, 124); + expect(txn.amountPaid, 124); + expect(txn.changeDue, 76); + expect(txn.isFullySettled, isTrue); + expect(txn.isSplit, isFalse); + expect(txn.invoiceNumber, contains('00001')); + expect(txn.status, TransactionStatus.completed); + }); + + test('decrements stock by the quantity sold', () async { + final cart = await milkCart(); + + await checkout( + cart: cart, + payments: const [ + PaymentSplit(method: PaymentMethod.cash, amount: 124, tendered: 124), + ], + cashierName: 'Suriya', + ); + + final milk = await products.findByBarcode('8901234500011'); + expect(milk!.stock, 48); + }); + + test('persists the transaction to history', () async { + final cart = await milkCart(); + + await checkout( + cart: cart, + payments: const [ + PaymentSplit(method: PaymentMethod.cash, amount: 124, tendered: 124), + ], + cashierName: 'Suriya', + ); + + final history = await transactions.history(); + expect(history, hasLength(1)); + expect(await transactions.salesTotalForDay(DateTime.now()), 124); + }); + + test('accepts a split across two tenders', () async { + final cart = await milkCart(); + + final result = await checkout( + cart: cart, + payments: const [ + PaymentSplit(method: PaymentMethod.cash, amount: 100, tendered: 100), + PaymentSplit( + method: PaymentMethod.upi, + amount: 24, + reference: 'UPI-991', + ), + ], + cashierName: 'Suriya', + ); + + expect(result.transaction.isSplit, isTrue); + expect(result.transaction.amountPaid, 124); + expect(result.transaction.paymentSummary, 'Cash + UPI'); + }); + + test('moves loyalty points and lifetime spend for a member', () async { + final cart = await milkCart(customerId: 'c001'); + + // 124 less the 2% silver discount, rounded. + expect(cart.membershipDiscountAmount, 2.48); + expect(cart.grandTotal, 122); + expect(cart.pointsEarned, 12); + + final result = await checkout( + cart: cart, + payments: const [ + PaymentSplit(method: PaymentMethod.cash, amount: 122, tendered: 200), + ], + cashierName: 'Suriya', + ); + + final updated = result.updatedCustomer!; + expect(updated.loyaltyPoints, 332); // 320 + 12 + expect(updated.lifetimeSpend, 24622); // 24500 + 122 + expect(updated.visitCount, 42); + }); + }); + + group('rejected checkout', () { + test('refuses an empty cart', () async { + expect( + () => checkout( + cart: Cart.empty, + payments: const [ + PaymentSplit(method: PaymentMethod.cash, amount: 0), + ], + cashierName: 'Suriya', + ), + throwsA(isA()), + ); + }); + + test('refuses a bill with no tender', () async { + final cart = await milkCart(); + expect( + () => checkout(cart: cart, payments: const [], cashierName: 'Suriya'), + throwsA(isA()), + ); + }); + + test('refuses an underpayment', () async { + final cart = await milkCart(); + expect( + () => checkout( + cart: cart, + payments: const [ + PaymentSplit(method: PaymentMethod.cash, amount: 100, tendered: 100), + ], + cashierName: 'Suriya', + ), + throwsA(isA()), + ); + }); + + test('refuses to sell more than is in stock', () async { + final cart = await milkCart(qty: 999); + expect( + () => checkout( + cart: cart, + payments: [ + PaymentSplit( + method: PaymentMethod.cash, + amount: cart.grandTotal, + tendered: cart.grandTotal, + ), + ], + cashierName: 'Suriya', + ), + throwsA(isA()), + ); + }); + + test('leaves stock untouched when validation fails', () async { + final cart = await milkCart(); + try { + await checkout(cart: cart, payments: const [], cashierName: 'Suriya'); + } on CheckoutFailure { + // expected + } + + final milk = await products.findByBarcode('8901234500011'); + expect(milk!.stock, 50); + }); + }); + + group('repositories', () { + test('finds a customer by mobile number', () async { + final found = await customers.findByMobile('9876543210'); + expect(found?.name, 'Abhishek'); + expect(await customers.findByMobile('0000000000'), isNull); + }); + + test('rejects a duplicate mobile number on create', () async { + // 9876543210 already belongs to the seeded customer c001. + expect( + () => customers.create( + const Customer(id: '', name: 'Impostor', mobile: '9876543210'), + ), + throwsA(isA()), + ); + }); + + test('creates a customer with a generated id and zeroed loyalty', () async { + final created = await customers.create( + const Customer(id: '', name: 'New Shopper', mobile: '9000011111'), + ); + + expect(created.id, isNotEmpty); + expect(created.loyaltyPoints, 0); + expect(created.lifetimeSpend, 0); + expect(created.tier, MembershipTier.bronze); + expect(await customers.findByMobile('9000011111'), isNotNull); + }); + + test('ranks an exact barcode above a fuzzy name match', () async { + final results = await products.search('8901234500011'); + expect(results.first.name, 'Amul Milk 1L'); + }); + + test('parks and resumes a bill', () async { + final cart = await milkCart(); + await transactions.park( + ParkedBill(id: 'park-1', cart: cart, parkedAt: DateTime.now()), + ); + + expect(await transactions.parkedBills(), hasLength(1)); + await transactions.removeParked('park-1'); + expect(await transactions.parkedBills(), isEmpty); + }); + }); +} diff --git a/test/unit/validators_test.dart b/test/unit/validators_test.dart new file mode 100644 index 0000000..813a3cc --- /dev/null +++ b/test/unit/validators_test.dart @@ -0,0 +1,91 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:nearle_pos/core/utils/formatters.dart'; +import 'package:nearle_pos/core/utils/validators.dart'; + +void main() { + group('Validators.mobile', () { + test('accepts a valid Indian number', () { + expect(Validators.mobile('9876543210'), isNull); + expect(Validators.mobile('6000000000'), isNull); + }); + + test('rejects the wrong length', () { + expect(Validators.mobile(''), isNotNull); + expect(Validators.mobile('98765'), isNotNull); + expect(Validators.mobile('98765432101'), isNotNull); + }); + + test('rejects a leading digit below 6', () { + expect(Validators.mobile('1234567890'), isNotNull); + expect(Validators.mobile('5876543210'), isNotNull); + }); + + test('ignores separators', () { + expect(Validators.mobile('98765 43210'), isNull); + expect(Validators.mobile('98765-43210'), isNull); + }); + }); + + group('Validators.emailOptional', () { + test('treats empty as valid, since email is optional', () { + expect(Validators.emailOptional(''), isNull); + expect(Validators.emailOptional(null), isNull); + }); + + test('accepts a well-formed address', () { + expect(Validators.emailOptional('a.b+tag@example.co.in'), isNull); + }); + + test('rejects a malformed address', () { + expect(Validators.emailOptional('not-an-email'), isNotNull); + expect(Validators.emailOptional('missing@tld'), isNotNull); + }); + }); + + group('Validators.name', () { + test('requires at least two characters', () { + expect(Validators.name('Jo'), isNull); + expect(Validators.name('J'), isNotNull); + expect(Validators.name(' '), isNotNull); + }); + }); + + group('Validators.isLikelyBarcode', () { + test('accepts a long digit string', () { + expect(Validators.isLikelyBarcode('8901234500011'), isTrue); + }); + + test('rejects short input and anything with letters', () { + expect(Validators.isLikelyBarcode('12345'), isFalse); + expect(Validators.isLikelyBarcode('milk'), isFalse); + expect(Validators.isLikelyBarcode('ABC1234567'), isFalse); + }); + }); + + group('Formatters', () { + test('groups a mobile number into 5 + 5', () { + expect(Formatters.mobile('9876543210'), '98765 43210'); + }); + + test('masks all but the last four digits', () { + expect(Formatters.maskedMobile('9876543210'), endsWith('3210')); + expect(Formatters.maskedMobile('9876543210'), isNot(contains('98765'))); + }); + + test('derives initials', () { + expect(Formatters.initials('Abhishek'), 'A'); + expect(Formatters.initials('Meena Lakshmi'), 'ML'); + expect(Formatters.initials(' '), '?'); + }); + + test('builds a sequential invoice number', () { + final n = Formatters.invoiceNumber(42, DateTime(2026, 7, 28)); + expect(n, 'INV-2607-00042'); + }); + + test('renders a percentage without noise decimals', () { + expect(Formatters.percent(0.05), '5%'); + expect(Formatters.percent(0.185), '18.5%'); + }); + }); +} diff --git a/test/widget/primary_button_test.dart b/test/widget/primary_button_test.dart new file mode 100644 index 0000000..b65311f --- /dev/null +++ b/test/widget/primary_button_test.dart @@ -0,0 +1,89 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:nearle_pos/core/widgets/primary_button.dart'; +import 'package:nearle_pos/core/widgets/status_pill.dart'; +import 'package:nearle_pos/domain/entities/customer.dart'; + +Widget _host(Widget child) => MaterialApp( + home: Scaffold(body: Center(child: child)), + ); + +void main() { + group('PrimaryButton', () { + testWidgets('renders its label', (tester) async { + await tester.pumpWidget( + _host(PrimaryButton(label: 'Charge', onPressed: () {})), + ); + + expect(find.text('Charge'), findsOneWidget); + }); + + testWidgets('fires onPressed when tapped', (tester) async { + var taps = 0; + await tester.pumpWidget( + _host(PrimaryButton(label: 'Charge', onPressed: () => taps++)), + ); + + await tester.tap(find.text('Charge')); + await tester.pump(); + + expect(taps, 1); + }); + + testWidgets('does nothing when onPressed is null', (tester) async { + await tester.pumpWidget( + _host(const PrimaryButton(label: 'Charge')), + ); + + await tester.tap(find.text('Charge'), warnIfMissed: false); + await tester.pump(); + + expect(find.text('Charge'), findsOneWidget); + }); + + testWidgets('shows a spinner instead of the label while busy', + (tester) async { + await tester.pumpWidget( + _host(PrimaryButton(label: 'Charge', busy: true, onPressed: () {})), + ); + + expect(find.byType(CircularProgressIndicator), findsOneWidget); + expect(find.text('Charge'), findsNothing); + }); + + testWidgets('renders a trailing total alongside the label', + (tester) async { + await tester.pumpWidget( + _host(PrimaryButton( + label: 'CHARGE', + onPressed: () {}, + trailing: const Text('\u20B9384.00'), + )), + ); + + expect(find.text('CHARGE'), findsOneWidget); + expect(find.text('\u20B9384.00'), findsOneWidget); + }); + }); + + group('StatusPill', () { + testWidgets('labels a membership tier', (tester) async { + await tester.pumpWidget(_host(StatusPill.tier(MembershipTier.silver))); + expect(find.text('SILVER'), findsOneWidget); + }); + + testWidgets('reports an out-of-stock product', (tester) async { + await tester.pumpWidget( + _host(StatusPill.stock(0, lowThreshold: 10)), + ); + expect(find.text('Out of stock'), findsOneWidget); + }); + + testWidgets('warns when stock is low', (tester) async { + await tester.pumpWidget( + _host(StatusPill.stock(4, lowThreshold: 10)), + ); + expect(find.text('4 left'), findsOneWidget); + }); + }); +} 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..fc96968 --- /dev/null +++ b/web/index.html @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + nearle_pos + + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..655de35 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "nearle_pos", + "short_name": "nearle_pos", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/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..3d606c8 --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(nearle_pos 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 "nearle_pos") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..9528a2a --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,17 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + AudioplayersWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin")); + PrintingPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("PrintingPlugin")); +} 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..1150ab0 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + audioplayers_windows + printing +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +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..394917c --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..3e1b585 --- /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 +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "nearle_pos" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "nearle_pos" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "nearle_pos.exe" "\0" + VALUE "ProductName", "nearle_pos" "\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..955ee30 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/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..f3f845b --- /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.Create(L"nearle_pos", 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..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3cb7146 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#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(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(target_length) > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/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..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_